React-intl for non components

后端 未结 5 2038
醉酒成梦
醉酒成梦 2021-02-05 17:14

Currently I have the following code to expose react-intl to non-components, but it throws an error for intl as undefined.

I have created a separate component as \'Curren

5条回答
  •  误落风尘
    2021-02-05 17:24

    There's also another way solving a similar problem to used react-intl formatMessage for non-components.

    Create a LocaleStore.js store file.

     import _formatMessage from "format-message";
    
        export default class LocaleStore {
    
          formatMessage = (id, values) => {
            if (!(id in this.messages)) {
              console.warn("Id not found in intl list: " + id);
              return id;
            }
            return _formatMessage(this.messages[id], values);
          };
        }
    

    import LocaleStore your CombinedStores.js

    import LocaleStore from "./stores/LocaleStore";
    import en from "./translations/en";
    import de from "./translations/de";
    import Global from "./stores/global"
    const locale = new LocaleStore("en", {
      en,
      de
    });
    export default {
    global:new Global(locale) 
    }
    

    now you can use this in your GlobalStore.js

        class GlobalStore {
        constructor(locale) {
         this.locale = locale;
        }
    
       formatMessage=(message_is,formatLanguage="en")=> {
         return  this.locale.formatMessage(message_id, formatLanguage);
        }
      }
    

提交回复
热议问题