反应本机导航setOptions问题

时间:2020-06-12 20:42:26

标签: react-native navigation

即使我尝试直接从导航文档中使用代码,我仍会收到此奇怪的错误,因此我认为导航堆栈出了点问题... 我不断收到的错误是:

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时,一切正常:)

2 个答案:

答案 0 :(得分:1)

由于您的代码表明您正在使用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

答案 1 :(得分:1)

您只需将“React”附加到“UseLayoutEffect”钩子即可。

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