反应本机导航集选项问题



即使我尝试直接从导航文档中使用代码,我也不断收到这个奇怪的错误,所以我认为我的导航堆栈有问题...... 我不断得到的错误是:

类型错误:未定义不是一个函数(靠近'...导航.设置选项...'(

这是我的导航堆栈:

import { createStackNavigator } from 'react-navigation-stack'; 
import { createAppContainer } from 'react-navigation';
import React from 'react';
import MainScreen from '../screens/MainScreen';
const screens = {
Main: {
screen: MainScreen,
navigationOptions: ({ navigation }) => ({
title: 'GRØFTA',
headerStyle: { backgroundColor: colour.blue, height: 150 },
headerTintColor: '#fff',
headerTitleStyle: { fontWeight: 'bold', fontSize: 40 },
headerTitleAlign: 'center',
headerLeft: () => <Icon
name='settings'
color='white'
size={30}
onPress={() => navigation.navigate("wouldYouRather")}
containerStyle={style = { paddingBottom: 70, paddingLeft: 8 }} />,
})
}, //And all my other screens
}
const MainStack = createStackNavigator(screens);
export default createAppContainer(
MainStack
)

这是我发生错误的主屏幕:

import React from 'react';
import { View, StyleSheet, TouchableOpacity, Text, Dimensions } from 'react-native';
import { useState, useEffect, useLayoutEffect } from 'react';
import { Icon } from 'react-native-elements'
export function MainScreen({ navigation }) {
const [showInfo, setShowInfo] = useState(false)
useLayoutEffect(() => {
navigation.setOptions({
headerRight: () => (
<Icon
name='more'
color='white'
size={30}
onPress={() => setShowInfo(!showInfo)}
containerStyle={style = { paddingBottom: 70, paddingRight: 8 }} />
),
});
}, [navigation]);
return ...
}

顺便说一句,当我删除使用布局效果时,一切正常:(

正如您的代码表明您正在使用react-navigation v4但您following the docs of react-navigation v5,原因是您收到此错误是因为setOptions do not exist in react-navigation v4.

按照这个反应导航 v4 的文档进行操作

https://reactnavigation.org/docs/4.x/getting-started

你只需要将"React"附加到"UseLayoutEffect"钩子上。

React.useLayoutEffect(() => {
navigation.setOptions({
headerRight: () => (
<Icon
name='more'
color='white'
size={30}
onPress={() => setShowInfo(!showInfo)}
containerStyle={style = { paddingBottom: 70, paddingRight: 8 }} />
),
});
}, [navigation]);

最新更新