在自己的函数中反应导航 onPress
React Navigation onPress in own function
我已经实现了教程中的 React Navigation 示例 https://reactnavigation.org/docs/intro/,它工作正常。
<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)
一切正常,您只需要绑定 _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>
);
}
或者在constructor
里面定义_btnToChat
方法的绑定:
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>
);
}
我已经实现了教程中的 React Navigation 示例 https://reactnavigation.org/docs/intro/,它工作正常。
<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)
一切正常,您只需要绑定 _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>
);
}
或者在constructor
里面定义_btnToChat
方法的绑定:
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>
);
}