首页 > 解决方案 > 你能在 React App 中拥有一个全局可访问的函数吗?

问题描述

我有一个函数用于字符串外部化来翻译和本地化网站的内容。

const t = (string_to_trans) => {
    return lang[string_to_trans];
}

我想让函数 t 在所有组件中全局访问。我发现我可以通过将它附加到全局或窗口来做到这一点

global.t = t

没有我的 App.js 文件,但是要调用它,我似乎必须使用

global.t('string_to_trans');

有没有办法不必使用全局或窗口来做到这一点,所以我可以只使用它来调用它

t('string_to_trans');

标签: reactjs

解决方案


做到这一点的 React 方法是使用 Context。https://reactjs.org/docs/context.html

<Context.Provider
    value={{
        translate: (string_to_trans) => lang[string_to_trans]
    }}
>
    {this.props.children}
</Context.Provider>

你甚至可以做

<Context.Provider value={lang}>{this.props.children}</Context.Provider>

然后直接访问组件内的翻译字典。


推荐阅读