zoukankan      html  css  js  c++  java
  • React i18n多语言实现

    目前比较流行的三种方式
    react-i18next
    react-intl
    react-intl-universa

    what is react-i18next?
    react-i18next is a powerful internationalization framework for React / React Native which is based on i18next(https://www.i18next.com).


    https://react.i18next.com/

    1.Install
    $ npm install react-i18next i18next --save

    2.Configure i18next

    3.Translate your content

    3.1使用 useTranslation hook

    import React from 'react';
    // the hook
    import { useTranslation } from 'react-i18next';
    function MyComponent () {
    const { t, i18n } = useTranslation();
    return <h1>{t('hello')}</h1> //你好!
    }
    

      

    3.withTranslation 使用高階組件 (HOC)

    import React from 'react';
    // the hoc
    import { withTranslation } from 'react-i18next';
    function MyComponent ({ t }) {
    return <h1>{t('hello')}</h1>
    }
    export default withTranslation()(MyComponent);
    

      

    3.3使用 render prop

    import React from 'react';
    // the render prop
    import { Translation } from 'react-i18next';
    export default function MyComponent () {
    return (
    <Translation>
    {
    t => <h1>{t('hello')}</h1>
    }
    </Translation>
    )
    }
    

      

    3.4使用 Trans 元件

    import React from 'react';
    import { Trans } from 'react-i18next';
    export default function MyComponent () {
    return (
    <Trans i18nKey="link">
    一起來
    <a>這裡</a>
    學習 React 吧
    </Trans>
    )
    }
    传参数的两种方式
    <Trans i18nKey="userMessagesUnread" values={{ name, count }}></Trans>
    
    
    <Trans i18nKey="userMessagesUnread_plural">{{ name, age, from }}</Trans>
    

      

    4.切換語言

    const { t, i18n } = useTranslation();
    const changeLanguage(lng: string)
    {
        i18n.changeLanguage(lng);
    }
    
    <button onClick={() => this.changeLanguage('zh')}>Chinese</button>
    
    <button onClick={() => this.changeLanguage('en')}>Engligh</button>
    

      

    人生旅途,边走边看...
  • 相关阅读:
    洛谷 1736 创意吃鱼法
    有多重限制的背包
    洛谷 1417 烹调方案
    2008 noip 传纸条
    环形石子合并 洛谷 1880 && hdu 3506 Monkey Party
    洛谷 1282 多米诺骨牌
    (金明的预算方案)依赖性的背包
    分组背包问题
    混合背包问题
    多重背包问题
  • 原文地址:https://www.cnblogs.com/dming4/p/15470592.html
Copyright © 2011-2022 走看看