关于国际版

78 阅读2分钟
  1. 切换按钮时更新当前语言
    • i18n.changeLanguage(当前语言)
    • setLocalStorage(当前语言)
    • window.language = 当前语言
  2. 将挂在在根元素上的组件卸载
    • ReactDOM.unmountComponentAtNode(根元素)
  3. 重新挂载组件
    • ReactDOM.render(component, 根元素)
  4. withTranslation 需要翻译的组件都会会用withTranslation这个高阶组件进行包裹

国际版的实现

  1. 首先在src/locales/cn以及src/locales/en文件夹下,分别建立两个同名json文件,里面存放的是对应的字段的中文翻译和英文翻译,例如:
//cn
{"hello": '你好‘}
//en
{"hello": "Hello"}
  1. 在需要进行翻译的组件中引入withTranslation这个高阶组件
import { withTranslation } from 'react-i18next';
function MyConponent() {
  return (<div>这里是组件</div>)
}
export default withTranslation('global')(MyComponent)
第一个参数是

withTranslation的第一个参数是该卡片对应的翻译的文件名,比如MyComponent对应了global,就是在第一步里配置的文件。 也可以传入多个:

export default withTranslation(['global', 'common'])(MyComponent)
  1. withTranslation的第二个参数传入组件,这样在组件的props中就可以拥有: t, lng等属性了。 组件中使用:
this.props.t('hello')

关于react-router

  1. Route

  2. Switch

  3. Redirect

  4. withRouter:withRouter是一个高阶组件,将组件包裹进Route里面,然后react-route的三个对象,location, history, match,就会被放进这个组件的props属性中,如果某个东西不是router,但是我们依靠他要进行路由的跳转,比如点击页面的logo跳转到首页,那么就可以用withRouter来做

<HashRouter>
  <Switch>
    <Route path="/" component={index}></Route>
    <Route path="/about" component={About}></Route>
    <Redirect to="/index"> 上面都未匹配到就会渲染Redict组件进行重定向
  </Switch>
</HashRouter>

exact的用法: 如果path为/about的话,那么根据上面的写法, index与about组件都会被渲染出来,所以如果想要只渲染出about的话,就加上exact

<Route exact path="/about" component={About}></Route>
  1. getUserConfirmation
<HashRouter getUserConfirmation={() => { Modal.confirm({ title: '确定离开当前页面么?' }) }}></HashRouter>

getUserConfirmation 用户离开当前组件时提示