【问题标题】:Undefined is not an object (evaluating 'navigation.getParam')未定义不是对象(评估“navigation.getParam”)
【发布时间】:2018-10-26 20:53:18
【问题描述】:

反应原生,反应导航。我有一个带有按钮的自定义标题,我已将其提取到另一个文件中。我似乎无法访问导航对象。

function SetNavOptions(title, navigation) {
    const { buttonStyle, iconStyle } = styles;
    return {
        headerBackground: (<LinearGradient
            colors={['#337ab7', '#265a88']}
            style={{ flex: 1 }}
            start={[0, 0]}
            end={[0, 1]}
        />),
        headerTitleStyle: {
            color: 'white',
        },
        headerTitle: title,
        headerLeft: (
            <TouchableOpacity onPress={() => navigation.getParam('mydrawer')} style={buttonStyle}>
                <View>
                    <Icon.FontAwesome
                        name='bars'
                        size={26}
                        style={iconStyle}
                    />
                </View>
            </TouchableOpacity>
        ),
    };
}

这是我设置 navigationOptions 变量的屏幕:

export default class HomeScreen extends React.Component {

  static navigationOptions = SetNavOptions('Topics', this.navigation);

  componentDidMount() {
    this.props.navigation.setParams({ mydrawer: this.openDrawer });
  }

  openDrawer = () => {
    this.props.navigation.navigate('myDrawer');
  };

}

运行代码并单击按钮,我得到“未定义不是对象(正在评估“navigation.getParam”)。我究竟做错了什么?另外,我如何定义 SetNavOptions() 是提取所有这些的最佳方式吗?我是 react-native 的新手。

【问题讨论】:

  • 你的堆栈导航器在哪里?
  • 很高兴发布它,但它只是一个标准的 createStackNavigator(),然后传递给 createBottomTabNavigator()。您是说应该在此处定义 navigationOptions 而不是每个屏幕?
  • 您的组件没有收到 navigation 属性(因此出现错误)。 createStackNavigator 应该注意这个
  • 是的,将导航选项放在那里会为您省去很多心痛
  • HomeScreen 正在导航。 componentDidMount() 函数完成时没有错误。是我试图从类函数外部引用导航吗?另外,如何设置createBottomTabNavigator 中的所有标题选项?文档中并不清楚。

标签: react-native react-navigation


【解决方案1】:

问题是我的static navigationOptions 行在HomeScreen 类中不正确。应该是这样的:

static navigationOptions = ({ navigation }) => SetNavOptions('Topics', navigation)

【讨论】:

    【解决方案2】:

    有类似的问题,route.params.mydrawer 而不是navigation.getParam('mydrawer') 解决了这个问题。看起来 React Native 路由器有一个更新,因为之前它与 navigation.getParam 打交道。

    灵感来自https://stackoverflow.com/a/64932908/11127383

    【讨论】:

      猜你喜欢
      • 2016-12-04
      • 2019-09-26
      • 2019-12-12
      • 2019-08-16
      • 2017-01-16
      • 2020-08-06
      • 2020-01-09
      • 2017-05-03
      • 2023-03-07
      相关资源
      最近更新 更多