react-native - React Navigation v5 setOptions 不起作用
问题描述
我正在尝试从组件内的堆栈屏幕设置导航选项,因为我需要使用屏幕上的特定操作呈现右标题按钮。问题是它不起作用。我使用的结构如下:
-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:我知道隐藏标题并为我的标题使用自定义组件可以解决问题,但我想知道为什么navigation.setOptions
不起作用。
任何帮助,任何想法将不胜感激,谢谢!
解决方案
这帮助了我。我通过危险的GetParent ()方法访问父堆栈导航器并设置它的选项来解决它。
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>
),
});
}
}, []);
推荐阅读
- python - MLPClassifier 只对不同的输入给出一个预测
- css - Next.js 全局 CSS 不能从您的自定义文件以外的文件导入
- python - 如何使用opencv消除小轮廓区域
- python - 带有 QIcon 的灰度 QPushButton 直到悬停
- reactjs - react router dom,替换浏览器url但不去页面
- php - $_POST["action"] == "编辑"
- basic - 在 Apple II、AppleDOS 3.3 上使用 Applesoft 的语法错误 GET
- node.js - 什么是 MongoDB 中的“连接”?
- c - 以 ' * ' 作为参数的错误
- reactjs - ReactJS POST fetch 不起作用,错误是:TypeError: Failed to fetch