在自己的函数中react导航 onPress

IT技术 reactjs react-native native react-native-navigation
2021-05-11 20:18:48

我已经在教程https://reactnavigation.org/docs/intro/ 中实现了 React Navigation 示例,它工作正常。

<Button
  onPress={() => navigate('Chat')}
  title="Chat with Lucy"
/>

我不想在 onPress 中直接调用导航,而是想在单独的函数 btnToChat 中调用它。我试图用 this.props.navigation.navigate 调用它,但它不起作用。你有什么建议吗?谢谢!

btnToChat(){
  console.log("test");
  this.props.navigation.navigate('Chat');    
}
render() {
  const { navigate } = this.props.navigation;
return (
  <View>
    <Button
      onPress={this._btnToChat}
    />
  </View>
    );
  }
}

出现如下错误:undefined is not an object (evaluating this.props.navigation)

1个回答

一切正常,您只需要绑定_btnToChat方法以访问其中的(正确上下文)this关键字。

像这样:

btnToChat = () => {                      //here use arrow  function
    console.log("test");
    this.props.navigation.navigate('Chat');    
}

render() {
    const { navigate } = this.props.navigation;
    return (
        <View>
            <Button
                onPress={this._btnToChat}
            />  
        </View>
    );
}

或者在_btnToChat里面定义方法的绑定constructor

constructor(){
   super();
   this._btnToChat = this._btnToChat.bind(this);
}

btnToChat (){           
    console.log("test");
    this.props.navigation.navigate('Chat');    
}

render() {
    const { navigate } = this.props.navigation;
    return (
        <View>
            <Button
                onPress={this._btnToChat}
            />  
        </View>
    );
}