在具有React Native 0.61.5/React 16.9.0
的React-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
的执行自动发生?
您的问题很简单,您只需要自己不打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
正如上述@ZacharyHaber所说,您只需要更改Button
组件onPress
处理程序。当您以以下onPress
形式将函数传递给onPress={handlePress()}
时,您正在告诉React调用该函数。
[只要您想使某个组件可通过某些功能单击,但不希望在安装时调用它,您只需通过排除()即onPress={handlePress}
来传递对该函数的引用。同样的概念也适用于通过道具将功能传递给子组件等。