在自己的功能中对onPress导航进行反应 [英] React Navigation onPress in own function

查看:98
本文介绍了在自己的功能中对onPress导航进行反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经按照教程 https://reactnavigation.org/docs/简介/,效果很好.

I've implemented the React Navigation example as in the tutorial https://reactnavigation.org/docs/intro/ and it works fine.

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

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

Instead of calling navigate direct in onPress, I want to call it in a separate function btnToChat. I've tried to call it with this.props.navigation.navigate, but it doesn't work. Do you have any suggestions? Thank you!

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

出现以下错误:undefined不是对象(正在评估this.props.navigation)

The following error appears: undefined is not an object (evaluating this.props.navigation)

推荐答案

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

Everything is proper, you just need to bind the _btnToChat method to access (correct context) this keyword inside that.

赞:

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>
    );
}

或在constructor内定义_btnToChat方法的绑定:

Or define the binding of _btnToChat method inside 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>
    );
}

这篇关于在自己的功能中对onPress导航进行反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆