reactjs - 你能在 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');
解决方案
做到这一点的 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>
然后直接访问组件内的翻译字典。
推荐阅读
- c# - 如何将路由数据从 ActionFilterAttribute 传递到操作方法?
- php - 如何在用户以外的列上调用急切加载?
- ios - 如何在调用 scrollviewdidscroll 委托时以自定义速度为 uiscrollview 滚动设置动画?
- android - 将文件上传到 Firebase Storage RxJava2
- node.js - 如何将容器内生成的 package-lock.json 文件传递给我的源代码?
- html - Firefox和Chrome中CSS行高中的箭头不同
- c++ - 求方程的根
- javascript - 如何在按下“Enter”键时调用函数
- c - 在文件上写入和读取链表堆栈不相同
- angular - 关于验证码授权实现的一个问题