如何从子组件导航到其他页面

时间:2020-07-10 13:34:46

标签: javascript reactjs react-native

我在'pages'文件夹中有Login.js和List.js,而在'component'文件夹中有Form.js。 Form.js是Login.js的子组件。当我想从Login.js导航到List.js时,我只使用onPress={() => this.props.navigation.navigate('List'),但是如果我在Form.js中使用相同的代码,它会说:Undefined不是对象(评估'_this2.props.navigation.navigate) ')

2 个答案:

答案 0 :(得分:1)

您可以将登录名中的函数传递给表单,以通过登录名执行该功能

功能组件表格

const Login = props => {
    const goToList = () => {
        this.props.navigation.navigate('List')
    }

    return (
        <Form redirectList={goToList} />
    )
}

const Form = props => {
    props.redirectList()  // This will execute the navigate from Login component
}

类组件形式

class Login extends React.Component {
    constructor(props){
        super();
        this.goToList = function(){
            this.props.navigation.navigate('List')
        }
    }

    render(){
        return (
            <Form redirectList={this.goToList} />
        )
    }
}

class Form extends React.Component {
    constructor(props){
        super();
        this.redirectToList = function(){
            props.redirectList();
        }
    }
    // You can redirect to list using
    this.redirectToList();
}

答案 1 :(得分:1)

我看不到您的代码,所以我无法告诉您这正是您要查找的内容,但是请尝试以下操作:

git commit -m "your commit message"