简体   繁体   English

调用从另一个文件导入的 function

[英]Call a function imported from another file

I have a function that I declared on a file, like this我在文件中声明了一个 function,就像这样

export default function doSomething (param1, param2, param3) {
 *Do something here*
}

And then I want to use that function whenever I press a button on a screen I have declared in another file:然后我想在我在另一个文件中声明的屏幕上按下按钮时使用 function:

import doSomething from '../../doSomething';

export default function Screen(props) {
 return (
   <Container>
      <SafeAreaProvider>
        <Button onPress={() => doSomething(1, 2, 3)} />
      </SafeAreaProvider>
   </Container>
 );
}

However, any time I press the button, it gives me a Invalid hook call. Hooks can only be called inside of the body of a function component但是,每当我按下按钮时,它都会给我一个Invalid hook call. Hooks can only be called inside of the body of a function component Invalid hook call. Hooks can only be called inside of the body of a function component error. Invalid hook call. Hooks can only be called inside of the body of a function component I'm fairly new to custom hooks/external functions, so how can I resolve is?我对自定义挂钩/外部函数还很陌生,那么我该如何解决呢?

If doSomething is a hook and not a plain JS function, then you can not just import it and call it as you would do with plain functions.如果doSomething是一个钩子而不是普通的 JS function,那么您不能像使用普通函数那样导入它并调用它。

The following code fixes the issue.下面的代码修复了这个问题。

export default function useDoSomething() {

   ...

  const doSomething = React.useCallback((parameter1, parameter2, parameter3) => {}, [])
  return {
    doSomething,
  }
}

Then use the hook as follows.然后按如下方式使用钩子。

const { doSomething } = useDoSomething()

return (
   <Container>
      <SafeAreaProvider>
        <Button onPress={() => doSomething(1, 2, 3)} />
      </SafeAreaProvider>
   </Container>
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM