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

标签 function listview react-native row components

我已经看到了这个问题的一些例子,但无法让任何一个工作,或者完全理解它是如何组合在一起的。我有一个名为 ParentListView 的组件另一个叫 ChildCell (listView 中的一行)我想要 onPress来自 ChildCell调用 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如果我将传入的 Prop 更改为:
<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()} />

它在 buttonPress 上崩溃并显示 Unhandled JS Exception: null is not an object (evaluating '_this2.onDonePressList')
更新 2:

好的,我已经尝试在构造函数中绑定(bind)方法,如下所示:
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

最佳答案

尝试调用onDonePresspressHandler像这样:

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

另外,绑定(bind)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

关于function - 从 React-Native ListView 行中的子组件调用父函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37173817/

相关文章:

function - grep 报告在上下文中包含函数名称

r - 在定义中使用省略号时如何在 R 函数调用中捕获错误或未定义的参数

c# - ListView 中的项目没有行缩进

java - 我如何从 firebase 检索数据到 android listview 的顶部

php - 使用关联数组作为 php 函数的输入

c - 我的函数显示正确的数字,但没有将其添加到变量中

android - 如何在另一个 Activity 上显示 ListView 所选项目的详细信息?

javascript - FlatList 不渲染图像

amazon-web-services - 从 React-Native 调用 AWS Lambda 函数

firebase - 安装 admob 模块后 react-native build 失败