首页 > 解决方案 > 未定义不是对象“this2.props.navigation.navigate”

问题描述

我无法在另一个页面上导航。我在这个类中有默认类代码,导航工作正常

export default class ClassName1 extends React.Component {
    constructor(props) {
        super(props);
    }
}

但是当我调用this.props.navigation下面的类时它会抛出一个错误

class ClassName2 extends React.Component {
     constructor(props) {
         super(props);
     }
}

像这样我在调用函数ClassName2

<TouchableOpacity onPress={() => this.props.navigation.navigate("Report") }>
    <Text style={style.modalContainerText}>
         inappropriate Content
    </Text>
</TouchableOpacity>

两个类都在一个文件中。

标签: react-nativereact-native-navigation

解决方案


如果您的类包含在StackNavigator函数中,您将可以访问,this.props.navigation否则您必须使用withNavigation如下函数

使用示例StackNavigator

import React, { Component } from 'react';
import { Button } from 'react-native';
import { StackNavigator } from 'react-navigation';

export class ClassName2 extends Component {
  render() {
    return <Button title="This will work" onPress={() => { this.props.navigation.navigate('someScreen') }} />;
  }
}

export const myStackNavigator = StackNavigator({
  myScreen: ClassName2
})

使用示例withNavigation

import React, { Component } from 'react';
import { Button } from 'react-native';
import { withNavigation } from 'react-navigation';

class ClassName2 extends Component {
  render() {
    return <Button title="This will work" onPress={() => { this.props.navigation.navigate('someScreen') }} />;
  }
}

export default withNavigation(ClassName2);

推荐阅读