How to implement localization in reactjs?

后端 未结 3 895
情深已故
情深已故 2021-02-02 12:33

We need to implement the localization in reactjs to define the string value(s). How can I implement that?

One link is there https://www.np

3条回答
  •  孤街浪徒
    2021-02-02 13:10

    npm install react-localization

    import ReactDOM from 'react-dom';
    import React, { Component } from 'react';
    import LocalizedStrings from 'react-localization';
    
    let strings = new LocalizedStrings({
      en:{
        how:"How do you want your egg today?",
        boiledEgg:"Boiled egg",
        softBoiledEgg:"Soft-boiled egg",
        choice:"How to choose the egg"
      },
      it: {
        how:"Come vuoi il tuo uovo oggi?",
        boiledEgg:"Uovo sodo",
        softBoiledEgg:"Uovo alla coque",
        choice:"Come scegliere l'uovo"
      }
     });
    
    class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          language: 'en'
        }
    
        this.handleLanguageChange = this.handleLanguageChange.bind(this);
      }
    
      handleLanguageChange(e) {
        e.preventDefault();
        let lang = e.target.value;
        this.setState(prevState => ({
          language: lang
        }))
      }
    
      render() {
        strings.setLanguage(this.state.language);
        return (
          
    Change Language:

    {strings.how}
    ) } } ReactDOM.render(, document.getElementById('root'));

    u can put your language specific data in a JSON file or or .js file. call that file in your current file and pass that object to new LocalizedStrings().

    Example: data.js

    const data = {
      en:{
        how:"How do you want your egg today?",
        boiledEgg:"Boiled egg",
        softBoiledEgg:"Soft-boiled egg",
        choice:"How to choose the egg"
      },
      it: {
        how:"Come vuoi il tuo uovo oggi?",
        boiledEgg:"Uovo sodo",
        softBoiledEgg:"Uovo alla coque",
        choice:"Come scegliere l'uovo"
      }
    }
    export {data};
    

    in your current file import it as import { data } from './data.js'; and then you can initialise as let strings = new LocalizedStrings({data});

提交回复
热议问题