微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我已经看到了这个问题的一些例子,但是无法让任何工作,或者完全理解它们如何组合在一起.我有一个名为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不是编译时的对象(评估’this.onDonePressList’)错误.

如果我直接把console.log放在这样:

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

它记录消息很好.

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

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

它在使用Unhandled JS异常的buttonPress上崩溃:null不是一个对象(评估’_this2.onDonePressList’)

更新2:

好的,我已经尝试在构造函数中绑定方法,如下所示:

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

但它给了我这个错误:null不是一个对象(评估’this.onDonePressList’)并且不会运行.

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

尝试在pressHandler中调用onDonePress,如下所示:
pressHandler() {
  this.props.onDonePress()
}

另外,将它绑定到renderRow和renderSectionHeader:

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

我使用上面的函数设置了一个示例here.

https://rnplay.org/apps/DcdAuw

原文地址:https://www.jb51.cc/react/300858.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐