我正在尝试从我的组件中的堆栈屏幕设置导航选项,因为我需要在我的屏幕上呈现具有特定操作的右标题按钮。问题是它不工作。 我使用的结构如下:
-StackNavigator
-MaterialTopTabNavigator
-tab1
-tab2
-tab3
当前代码:
//My navigation
<NavigationContainer initialState={initialState} ref={ref}>
<Stack.Navigator screenOptions={{ headerShown: false }}>
//some other Stacks
<Stack.Screen
name="Detail"
component={DetailTabScreen}
options={{
headerShown: true, //header works ok
headerRight: () => ( //this would work
<View style={{backgroundColor: 'red', width: 100}}/>
)
}}
/>
</Stack.Navigator>
</NavigationContainer>
我的 DetailTabScreen:
const TopTab = createMaterialTopTabNavigator()
const DetailTabScreen = () => (
<StoreProvider>
<SafeAreaView style={{ flex: 1 }}>
<TopTab.Navigator
tabBarOptions={{
...options
}}
>
<TopTab.Screen
name="PlanDetail"
component={PlanDetail}
options={{
tabBarLabel: ({ color }: TabBarLabelProps) => (
<Text>Detalles</Text>
),
}}
/>
<TopTab.Screen
name="PlanChat"
component={PlanChat}
options={{
tabBarLabel: ({ color }: TabBarLabelProps) => (
<Text>Chat</Text>
),
}}
/>
<TopTab.Screen
name="Participants"
component={Participants}
options={{
tabBarLabel: ({ color }: TabBarLabelProps) => (
<Text>Participantes</Text>
),
}}
/>
</TopTab.Navigator>
</SafeAreaView>
</StoreProvider>
)
我已经尝试按照文档建议使用 useLayoutEffect
设置组件内的选项,也尝试使用 useEffect
:
useLayoutEffect(() => {
props.navigation.setOptions({
headerRight: () => (//does not work
<TouchableOpacity
onPress={() => console.warn('This is a button!')}
style={{marginRight:16}}
>
<Icon name={Platform.OS === 'ios' ? 'share-apple' : 'share-google'} type="EvilIcons" style={{ color: colors.darkGreen, marginright: 16 }} />
</TouchableOpacity>
),
});
}, []);
PS:我知道隐藏 header 并为我的 header 使用自定义组件可以解决这个问题,但我想知道为什么 navigation.setOptions
不起作用。
任何帮助,任何想法将不胜感激,谢谢!
最佳答案
This帮助我。 我通过 dangerouslyGetParent() 方法访问父堆栈导航器并设置它的选项来解决它。
useLayoutEffect(() => {
const stackNavigator = props.navigation.dangerouslyGetParent(); // this is what you need
if (stackNavigator) {
stackNavigator.setOptions({
headerRight: () => (
<TouchableOpacity
onPress={() => console.warn("This is a button!")}
style={{ marginRight: 16 }}
>
<Icon
name={Platform.OS === "ios" ? "share-apple" : "share-google"}
type="EvilIcons"
style={{ color: colors.darkGreen, marginright: 16 }}
/>
</TouchableOpacity>
),
});
}
}, []);
关于react-native - React Navigation v5 setOptions 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63771527/