一個簡單且靈活易用的 React 格式化和 i18n 工具

Eric發表於2017-01-21

react-put 是一個簡單且靈活易用的格式化和 i18n 工具。

它通過“連線”元件給元件一個預設為 putpropsput 是一個可以根據不同的 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);

相關文章