我已经看到了这个问题的一些例子,但无法让任何一个工作,或者完全理解它是如何组合在一起的。我有一个名为 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
最佳答案
尝试调用onDonePress
在 pressHandler
像这样:
pressHandler() {
this.props.onDonePress()
}
另外,绑定(bind)
this
给您的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
关于function - 从 React-Native ListView 行中的子组件调用父函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37173817/