如何防止useLayoutEffect定义的按钮功能在渲染后自动执行

问题描述 投票:-1回答:2

在具有React Native 0.61.5/React 16.9.0React-Navigation 5.x应用中,标题中的按钮由navigation.setOptions中的useLayoutEffect定义。这是功能组件Chat中的代码部分:

useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => (
        <Button onPress={handleAddPicture()} title="Image Picker" />  //handleAddPicture is defined in the same component
      ),
    });
  }, []);

useEffect(() => {
  //retrieve data from backend server
}, [])

useLayoutEffect用于在标题中添加按钮,以便用户在本地文件系统上拾取图像。问题在于,一旦渲染了组件,就会以某种方式自动单击图像选择器按钮,并调用handleAddPicture函数。如何防止handleAddPicture的执行自动发生?

reactjs react-hooks react-navigation
2个回答
0
投票

您的问题很简单,您只需要自己不打handleAddPicture。当按下Button时,将调用绑定到onPress的代码,因此您只需从其删除括号即可使用。

useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => (
        <Button onPress={handleAddPicture} title="Image Picker" />  //handleAddPicture is defined in the same component
      ),
    });
  }, []);

useEffect(() => {
  //retrieve data from backend server
}, [])|

请注意,如果您要自己调用该函数或执行除该函数调用之外的其他操作,也可以像这样使用它。

        <Button onPress={()=>handleAddPicture()} title="Image Picker" />  //handleAddPicture is defined in the same component

0
投票

正如上述@ZacharyHaber所说,您只需要更改Button组件onPress处理程序。当您以以下onPress形式将函数传递给onPress={handlePress()}时,您正在告诉React调用该函数。

[只要您想使某个组件可通过某些功能单击,但不希望在安装时调用它,您只需通过排除()即onPress={handlePress}来传递对该函数的引用。同样的概念也适用于通过道具将功能传递给子组件等。

© www.soinside.com 2019 - 2024. All rights reserved.