一个简单且灵活易用的 React 格式化和 i18n 工具

来源:转载

react-put 是一个简单且灵活易用的格式化和 i18n 工具。


它通过“连接”组件给组件一个默认为 put 的 props。put 是一个可以根据不同的 key 显示不同内容的函数。 key 和 内容之间的关系可以灵活地通过配置确定。


NPM
GitHub
在线互动演示


最简单的使用方式:


// App.js
import connectPut from "react-put"

class App extends Component {
render() {
return (
<div>
<p>{this.props.put('hello')}, {this.props.put('welcome', 'username')}</p>
<p>{this.props.put('haveApple', 'username', 3)}</p>
<p>{this.props.put('testKey')}</p>
</div>
);
}
}
const options = {
dictionary: {
hello: '你好',
welcome: name => `欢迎${name}`,
haveApple: (name, amount) => `${name} has ${amount} ${amount === 1 ? 'apple' : 'apples'}`,
},
mapPropToDictionary: props => props, // You can do something wild with this option
};
export default connectPut(options)(App);

// test.js
import App from './App';

...
render() {
return <App testKey='someValue' />
}
...

// renders:
<div>
<p>你好, 欢迎username</p>
<p>username has 3 apples</p>
<p>someValue</p>
</div>

也可与 redux 相连


class App extends Component {
constructor(props) {
super(props);
this.changeLanguage = () => {
this.props.dispatch({ type: 'SET_DICT', dictionary: {...} }); // Assume SET_DICT is received by dictionary reducer
};
}
render() {
return (
<div>
<p>{this.props.put('hello')}, {this.props.put('welcome', 'username')}</p>
<p>{this.props.put('haveApple', 'username', 3)}</p>
<p>{this.props.put('testKey')}</p>
<button onClick={this.changeLanguage}>Change Language</button>
</div>
);
}
}
const options = {
mapPropToDictionary: props => Object.assign({}, props.dictionary),
};
const mapStateToProps = state => Object.assign({}, { dictionary: state.dictionary });
ConnectedApp = connectPut(options)(App);
ConnectedApp = connect(mapStateToProps)(ConnectedApp);

分享给朋友:
您可能感兴趣的文章:
随机阅读: