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>
    

      

    人生旅途,边走边看...
  • 相关阅读:
    前端之 http
    事务、存储、索引与慢查询及数据库设计的三大范式
    Navcat 软件使用及 pymysql模块
    MySQL单表查询与多表查询
    IO 模型
    Unable to round-trip http request to upstream: read tcp 192.168.xx.xxx:xxxxx->xx.xxx.xxx.x:xxx: read: operation timed out
    恶补计算机基础知识(一)
    2020 年终总结
    自我总结Java并发编程基础篇(一)
    jvm系列(三):GC算法、垃圾收集器
  • 原文地址:https://www.cnblogs.com/dming4/p/15470592.html
Copyright © 2011-2022 走看看