我们需要在reactjs中实现本地化来定义字符串 值(S)。我该如何实现呢?
有一个链接https://www.npmjs.com/package/react-localization,但我没有得到添加它的步骤。
我尝试过以下步骤: -
我在ES6中添加我的组件: -
class Home扩展了React.Component { 构造函数(道具){ 超级(道具);
}
render() {
return (
<Text>{strings.how}
</Text>
);
}
}
我已将本地化代码添加为: -
从'react-localization'导入LocalizedStrings;
let strings = new LocalizedStrings({
en:{
how:"How do you want your egg today?",
boiledEgg:"Boiled egg",
softBoiledEgg:"Soft-boiled egg",
choice:"How to choose the egg"
},
it: {
how:"Come vuoi il tuo uovo oggi?",
boiledEgg:"Uovo sodo",
softBoiledEgg:"Uovo alla coque",
choice:"Come scegliere l'uovo"
}
});
现在,如果您将看到上述内容: - {strings.how} 我应该可以 获取字符串值,因为它在本地化中定义,但我不是 能够做到。
答案 0 :(得分:9)
雅虎已经创建了一个用于在React中实现本地化的软件包,可能正是您所寻找的:https://github.com/yahoo/react-intl。它负责“日期,数字和字符串,包括复数和处理翻译”。
答案 1 :(得分:2)
npm install react-localization
import ReactDOM from 'react-dom';
import React, { Component } from 'react';
import LocalizedStrings from 'react-localization';
let strings = new LocalizedStrings({
en:{
how:"How do you want your egg today?",
boiledEgg:"Boiled egg",
softBoiledEgg:"Soft-boiled egg",
choice:"How to choose the egg"
},
it: {
how:"Come vuoi il tuo uovo oggi?",
boiledEgg:"Uovo sodo",
softBoiledEgg:"Uovo alla coque",
choice:"Come scegliere l'uovo"
}
});
class App extends Component {
constructor(props) {
super(props);
this.state = {
language: 'en'
}
this.handleLanguageChange = this.handleLanguageChange.bind(this);
}
handleLanguageChange(e) {
e.preventDefault();
let lang = e.target.value;
this.setState(prevState => ({
language: lang
}))
}
render() {
strings.setLanguage(this.state.language);
return (
<div>
Change Language: <select onChange={this.handleLanguageChange}>
<option value="en">En- English</option>
<option value="it">It- Italian</option>
</select>
<br /><br />
{strings.how}
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'));
u可以将特定于语言的数据放入JSON文件或.js
文件中。在当前文件中调用该文件,然后将该对象传递给new LocalizedStrings()
。
示例: data.js
const data = {
en:{
how:"How do you want your egg today?",
boiledEgg:"Boiled egg",
softBoiledEgg:"Soft-boiled egg",
choice:"How to choose the egg"
},
it: {
how:"Come vuoi il tuo uovo oggi?",
boiledEgg:"Uovo sodo",
softBoiledEgg:"Uovo alla coque",
choice:"Come scegliere l'uovo"
}
}
export {data};
在当前文件中将其导入为import { data } from './data.js'
;
然后您可以初始化为let strings = new LocalizedStrings({data});
答案 2 :(得分:2)
我们使用react-i18next。然后使用i18nexus自动翻译和管理翻译。