React Native Navigation setOptions 问题

React Native Navigation setOptions issue

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

TypeError: undefined 不是一个函数(靠近'...navigation.setOptions...')

这是我的导航堆栈:

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 ...
}

顺便说一句,当我删除 useLayoutEffect 时,一切正常:)

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

遵循 react-navigation 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]);