const App = () => {
return (
<NavigationContainer>
{/* <LeftSideMenu /> */}
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
style={styles.title}
options={{
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>
);
};
I want to change screen through the right header button
In the headerRight how can it changing screen from Home to Profile?
Now it comes up with error: Can't find variable: navigation
you can use useNavigation hook for this purpose.
import { useNavigation, CommonActions } from '@react-navigation/native';
in your component just create hook and use like this.
const navigation = useNavigation();
<TouchableOpacity
style={{ marginRight: 10 }}
onPress={() => {
navigation.dispatch(CommonActions.navigate('Confirm'));
}}>
</TouchableOpacity>
Here is my example to achieve this kind of situation.
<Stack.Screen
name="MyOrders"
component={MyOrderScreen}
options={{
headerRight: () => <HeaderRight />,
title: 'My Orders',
headerTitleAlign: 'center'
}}
/>
Here i am creating screens in my stack and using header in separate component.
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>
);
};
You can access navigation with minimal code changes by simply passing a function to the options prop like so.
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>
);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.