React Native 在功能组件之间共享常量和钩子

时间:2021-07-29 14:36:26

标签: reactjs react-native react-hooks

我的问题在标题中:在 React Native 中,是否可以在多个功能组件之间共享钩子?例如,如果我想在函数组件之间共享函数和常量,我可以这样做:

File1.tsx:

//outside the functional component
export const _file1function = function(){
   return "This came from file1" ;
}
export default function File1 () {
  ....
}

File2.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 的基本原理?

2 个答案:

答案 0 :(得分:0)

您将编写一个自定义钩子来在功能组件之间共享逻辑

export default function useMyHook() {
   const [test, setTest] = React.useState(0);

   const _hookfunction = function(){
       setTest(1);
       return true;
   };

   // Then you can return anything you want
   return [test, _hookfunction];
}

在你的组件中

export default function HookTest() {
   const [test, setTest] = useMyHook();
}

答案 1 :(得分:0)

如果您需要每个组件都访问对相同值的相同引用,那么您需要使用 React Context

如果你想看一些例子,这里有一些链接: