ReactNative - ListView中的Tapping行给出错误:无法读取null的属性`_pressRow`

nbu*_*urk 7 javascript listview reactjs react-native

我正在使用一个构建一个小的ReactNative + Redux应用程序ListView.我正在关注文档中的示例代码,并提出了以下设置.我当前的实现非常接近示例代码,但由于某些原因,当我想"单击"列表项时,我收到错误.

以下是我的代码中的相关部分:

JobsRootComponent.js

class JobsRootComponent extends Component {

  ...

  _pressRow(row) {
      console.log('JobsRootComponent - _pressRow ', row)
  }

  ...

  _renderRow(rowData, section, row) {
      const title = rowData.title
      const subtitle = 'by ' + rowData.by
      return (
         <TouchableHighlight onPress={() => this._pressRow(row)}>
           <View style={styles.cellContainer}>
             <Text style={styles.cellTitle}>{title}</Text>
             <Text style={styles.cellSubtitle}>{subtitle}</Text>
           </View>
         </TouchableHighlight>          
      )
  }

  ...

  render() {
    return (
        <ListView
          style={styles.container}
          dataSource={this.props.dataSource}
          renderRow={this._renderRow}
        />
      )
  }

  ...

}
Run Code Online (Sandbox Code Playgroud)

这段代码对我来说很好,但出于某种原因,当点击列表项时,javacript崩溃并在chrome dev控制台中显示以下两个错误:

  1. 无法读取性能_pressRownull
  2. 未处理的异常JS:无法读取性能_pressRownull

根据我的理解,这意味着_pressRow实际上属性是以点击为目标的对象null.但那个对象不应该是我的JobsRootComponent吗?怎么可能null在这一点上?

nbu*_*urk 11

在搜索了一段时间后,我遇到了这个教程,描述了如何实现一个简单的ToDo-app,它帮助我自己解决了这个问题.

问题是由于我分配_renderRowrenderRow-property的方式ListView:而不是简单地做renderRow={this._renderRow},我需要使用javascript的bind()功能:renderRow={this._renderRow.bind(this).

作为参考,这是我的render()方法现在的样子:

render() {
  return (
      <ListView
        style={styles.container}
        dataSource={this.props.dataSource}
        renderRow={this._renderRow.bind(this)}
      />
    )
}
Run Code Online (Sandbox Code Playgroud)