【发布时间】:2021-07-29 14:36:26
【问题描述】:
我的问题在标题中:在 react native 中,是否可以在多个功能组件之间共享 hooks?例如,如果我想在功能组件之间共享函数和常量,我可以这样做:
文件1.tsx:
//outside the functional component
export const _file1function = function(){
return "This came from file1" ;
}
export default function File1 () {
....
}
文件2.tsx:
import * as f1 from './File1'
export default function File2 () {
...
f1._file1function() //is valid
...
}
但是,如果我尝试复制类似的行为,并使用挂钩导出常量:
export const [test, setTest] = React.useState(0);
export const _hookfunction = function(){
setTest(1);
return true;
}
我收到以下错误:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
因此,我似乎只需将这些常量和函数放在一个函数组件中,如下所示:
export default function HookTest() {
const [test, setTest] = React.useState(0);
const _hookfunction = function(){
setTest(1);
return true;
}
}
现在这看起来像是一个使用钩子的普通反应原生应用程序。如何从另一个脚本访问这些函数和常量?功能组件和屏幕之间可以共享钩子吗?如果没有,是否有其他方法可以获得这种行为,或者这是否完全违背了 React 的基本原理?
【问题讨论】:
-
你可以编写一个自定义钩子,但是你希望每个组件共享相同的
test值吗?如果一个组件更新了该值,其他组件需要接收更新的值吗? -
是的,我希望在访问它的所有组件之间共享该值
标签: reactjs react-native react-hooks