我正在使用React Context API以多种语言显示我的站点。除了当我尝试在我的文本区域中插入一个占位符时,它显示[object Object]
之外,一切都正常工作。如果我在实际中使用相同的组件,例如在
标签正确显示!
import React, { Component } from "react";
import Translate from '../translations/Translate'
class FormEntry extends Component {
render() {
return (
<div className="inputArea shadow">
<textarea
className="dataInputChild"
placeholder={<Translate string={'submitbox.copy-and-paste'}/>}//this displays [object Object]
/>
<p><Translate string={'submitbox.copy-and-paste'}/></p> //this displays the desired text
</div>
);
}
}
export default FormEntry;
Translate组件如下所示:
import React, { PureComponent } from "react";
import en from "./en.json";
import es from "./es.json"; //these are the dictionary files
import cn from "./cn.json";
LanguageContext = React.createContext()
export default class Translate extends PureComponent {
constructor(props) {
super(props);
this.state = {
langs: {
en,
es,
cn
}
};
}
render() {
const {langs} = this.state
const {string} = this.props
return (
<LanguageContext.Consumer>
{value => langs[value][string]}
</LanguageContext.Consumer>
);
}
}
有没有人看到我做错了什么?
谢谢!
发布于 2019-02-02 10:31:29
为了扩展Estus' answer,只需创建一个单独的函数,它接受语言、语言值和字符串(就像您在render
方法中的Translate
组件中所做的那样),并在需要的地方重用它。
您将把上下文从实际功能中分离出来,并且可以像这样重用函数:(或者在您可以访问上下文的任何其他组件中)。
// langs -> coming from context or some map of languages you use
// langValue -> coming from the context API
// 'submitbox.copy-and-paste' -> the actual string you want to translate
const translation = translate(langs, langValue, 'submitbox.copy-and-paste');
// and then use the variable in as placeholder and the <p> tag
// or if different string values see below
<div className="inputArea shadow">
<textarea
className="dataInputChild"
placeholder={translate(langs, langValue, 'submitbox.copy-and-paste')}
/>
<p>{translate(langs, langValue, 'submitbox.copy-and-paste')}/></p>
</div>
发布于 2019-02-02 10:06:34
<Translate string={'submitbox.copy-and-paste'}/>
是React元素,它是一个对象。它不能作为placeholder
属性提供,因为需要字符串。
FormEntry
组件可以使用contextType
来访问上下文。这限制了组件只能使用单个上下文。
https://stackoverflow.com/questions/54491455
复制