javascript - 无法在另一个方法内调用导航

标签 javascript react-native

我正在尝试使用 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 bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.

这是文档:

Handling events

关于javascript - 无法在另一个方法内调用导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46458587/

相关文章:

javascript - 当特定 props 元素发生更新时,React Hooks 会更新状态元素

Javascript JsTestDriver Jasmine 和 Jasmine-jquery

javascript - Redux 表单 onSubmit 在测试中值空对象

javascript - 设置表单控制错误 - 错误名称是变量

ios - 你如何隐藏 React Native iOS 模拟器中的警告?

react-native - npm 包导出路径定义

android - 带有 Json Api 的 ReactNative ListView

javascript - 如何设置其类根据 Svelte 中的 `use` 指令而更改的组件的样式?

javascript - 动态图表无法正常工作(highcharts)?

javascript - 无法正确 trim 和粗体匹配两个字符串中的单词