我的 HomeHeader 组件是这样的:
import React from "react";
import { View, StyleSheet, Text, Image } from "react-native";
import Icon from "react-native-vector-icons/FontAwesome5";
export default function HomeHeader({ navigation }) {
return (
<View style={styles.home_header}>
<Icon
style={styles.menu}
name="bars"
size={30}
color="white"
onPress={navigation.toggleDrawer()}
/>
<Image
style={styles.header_logo}
source={require("../assets/logo.png")}
/>
<Text>Hello</Text>
</View>
);
}
我在我的主屏幕上使用它是这样的:
return (
<View>
<HomeHeader navigation={navigation} />
</View>
)
但我收到此错误消息:
Warning: Cannot update a component from inside the function body of a different component.
我想做的是,我将主屏幕的标题部分分离到一个名为 HomeHeader 的单独组件中。在这个组件中,我附加了事件处理程序来切换 DrawerNavigation(左侧抽屉菜单)的打开/关闭
如果我在我的主屏幕中创建一个按钮并添加事件处理程序来切换抽屉,它工作正常。但是只有当我从我的 HomeHeader 组件中尝试这个时才会出现这个问题。
顺便说一句,我正在使用 ReactNavigation v5,我什至尝试过这个方法:https://reactnavigation.org/docs/connecting-navigation-prop/
到目前为止运气不好。
最佳答案
将 onPress={ navigation.toggleDrawer() }
更改为 onPress={ ()=> navigation.toggleDrawer() }
您可以在 here 中阅读更多相关信息
关于react-native - React Native 无法从 > 不同组件的函数体内部更新组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62938444/