我正在尝试使用 react 导航导航到另一个屏幕。但是,使用此代码时,我收到错误: undefined is not an object (evaluation 'this.props.navigation')
直接调用navigate
(请参阅底部的示例)时,它可以工作。
我做错了什么?
这不起作用:
_renderRow (rowData) {
return (
<View >
<TouchableHighlight onPress={this._handlePress} underlayColor='white'>
<Image
style={{width: 50, height: 50}}
source={{uri: 'http://openweathermap.org/img/w/' + rowData.iconName + '.png'}}
/>
</TouchableHighlight>
</View>
)
}
_handlePress () {
this.props.navigation.navigate('Details')
}
这确实有效:
_renderRow (rowData) {
return (
<View >
<TouchableHighlight onPress={() => this.props.navigation.navigate('Details')} underlayColor='white'>
<Image
style={{width: 50, height: 50}}
source={{uri: 'http://openweathermap.org/img/w/' + rowData.iconName + '.png'}}
/>
</TouchableHighlight>
</View>
)
}
最佳答案
您需要绑定(bind)上下文。 onPress={this._handlePress.bind(this)}
将完成这项工作。
You have to be careful about the meaning of
this
in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bindthis.handleClick
and pass it toonClick
, this will beundefined
when the function is actually called.
这是文档:
关于javascript - 无法在另一个方法内调用导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46458587/