【发布时间】:2016-09-07 12:21:15
【问题描述】:
我已经看到了这个问题的几个例子,但无法让任何一个工作,或者完全理解它是如何组合在一起的。我有一个名为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()} />
它在 buttonPress 上崩溃,Unhandled JS Exception: null is not an object (evaluating '_this2.onDonePressList')
更新 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') 并且不会运行。
【问题讨论】:
-
您是否尝试过使用构造函数编写组件?根据反应文档:“我们建议您在构造函数中绑定事件处理程序,以便每个实例只绑定一次”facebook.github.io/react/docs/reusable-components.html
-
我试过(见更新 2)但无济于事。
() => myFunction()不帮我绑定吗?
标签: function listview react-native row components