Thread1
我想通过右侧标题按钮更改屏幕
标题右侧,如何将屏幕从主页更改为个人资料?
现在出现错误:找不到变量:导航
答案 0 :(得分:2)
您可以为此使用useNavigation挂钩。
import { useNavigation, CommonActions } from '@react-navigation/native';
只需在组件中创建钩子并像这样使用即可。
const navigation = useNavigation();
<TouchableOpacity
style={{ marginRight: 10 }}
onPress={() => {
navigation.dispatch(CommonActions.navigate('Confirm'));
}}>
</TouchableOpacity>
这是我解决这种情况的例子。
<Stack.Screen
name="MyOrders"
component={MyOrderScreen}
options={{
headerRight: () => <HeaderRight />,
title: 'My Orders',
headerTitleAlign: 'center'
}}
/>
在这里,我正在堆栈中创建屏幕,并在单独的组件中使用标题。
const HeaderRight = () => {
const navigation = useNavigation();
return (
<View
style={{
flexDirection: 'row',
alignItems: 'center',
marginRight: 10
}}
>
<TouchableOpacity
style={{ marginRight: 10 }}
onPress={() => {
navigation.dispatch(CommonActions.navigate('Chats'));
}}
>
</TouchableOpacity>
</View>
);
};
答案 1 :(得分:1)
像这样简单地将函数传递给options属性,就可以以最小的代码更改访问导航。
const App = () => {
return (
<NavigationContainer>
{/* <LeftSideMenu /> */}
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
style={styles.title}
options={({navigation}) => ({ // only change
title: 'HOME',
headerTintColor: Colors.primary,
headerTitleStyle: {
fontWeight: 'bold',
},
headerRight: () => (
<Button onPress={() => navigation.navigate('Profile')} title="Profile" />
),
})}
/>
<Stack.Screen name="Profile" component={ProfileScreen} />
</Stack.Navigator>
</NavigationContainer>
);
};