从 React-Native ListView 行中的子组件调用父函数

Call parent function from child component in React-Native ListView row

我看过这个问题的几个例子,但无法解决,也无法完全理解它们是如何组合在一起的。我有一个名为 ParentListView 的组件和另一个名为 ChildCell 的组件(listView 中的一行)我希望 ChildCell 中的 onPress 调用 ParentListView 中的函数.

class ChildCell extends Component {

  pressHandler() {
    this.props.onDonePress;
  }

  render() {
    return (
        <TouchableHighlight onPress={() => this.pressHandler()} >
          <Text>Child Cell Button</Text>
        </TouchableHighlight>
    );
  }

}

并在 ParentListView 中:

class ParentListView extends Component {  

//...

  render() {

    return (
      <ListView
        dataSource={this.state.dataSource}
        style={styles.listView}
        renderRow={this.renderCell}
        renderSectionHeader={this.renderSectionHeader}
        />
    );
  }

  renderCell() {
    return (
      <ChildCell onDonePress={() => this.onDonePressList()} />
    )
  }

  onDonePressList() {
    console.log('Done pressed in list view')
  }

}

我认为这就是所有相关的代码。我可以让媒体注册希望 ChildCell,但无法让方法在 ParentListView 中触发。我错过了什么?

提前致谢!

更新 1:

ParentListView 中,如果我更改传入的道具:

<ChildCell onDonePress={this.onDonePressList.bind(this)} />

我在渲染单元格时在编译时遇到 Unhandled JS Exception: null is not an object (evaluating 'this.onDonePressList') 错误。

如果我像这样直接把console.log放进去:

<ChildCell onDonePress={() => console.log('Done pressed in list view')} />

它可以很好地记录消息。

如果我像原来那样离开它:

<ChildCell onDonePress={() => this.onDonePressList()} />

它在使用 Unhandled JS Exception: null is not an object (evaluating '_this2.onDonePressList')

的 buttonPress 时崩溃

更新 2:

好的,我试过像这样在构造函数中绑定方法:

class ParentListView extends Component {
  constructor(props) {
    super(props);
    this.onDonePressList = this.onDonePressList.bind(this);
    this.state = {...};
}

但它给我这个错误:null is not an object (evaluating 'this.onDonePressList') 并且不会 运行。

更新 3: Here is a link to a react native playground

尝试像这样在 pressHandler 中调用 onDonePress

pressHandler() {
  this.props.onDonePress()
}

此外,将 this 绑定到您的 renderRowrenderSectionHeader:

<ListView
    dataSource={this.state.dataSource}
    style={styles.listView}
    renderRow={this.renderCell.bind(this)}
    renderSectionHeader={this.renderSectionHeader.bind(this)}
    />

我已经使用上述函数设置了一个示例 here

https://rnplay.org/apps/DcdAuw