【问题标题】:React Native Navigation setOptions issueReact Native Navigation setOptions 问题
【发布时间】:2020-06-12 20:42:26
【问题描述】:

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

TypeError: undefined is not a function (near '...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 版本?

标签: react-native navigation


【解决方案1】:

正如您的代码所暗示的,您使用的是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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-25
      • 1970-01-01
      • 2017-11-28
      • 1970-01-01
      • 2019-02-28
      • 1970-01-01
      • 1970-01-01
      • 2017-10-24
      相关资源
      最近更新 更多