Mic*_*all 7 listview components row function react-native
我已经看到了这个问题的一些例子,但无法让任何工作,或完全理解它们如何组合在一起.我有一个被调用的组件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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
并在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')
}
}
Run Code Online (Sandbox Code Playgroud)
我认为这就是所有相关的代码.我可以让媒体注册希望ChildCell,但无法获得该方法ParentListView.我错过了什么?
提前致谢!
更新1:
在ParentListView如果我改变传递到这个道具:
<ChildCell onDonePress={this.onDonePressList.bind(this)} />
Run Code Online (Sandbox Code Playgroud)
Unhandled JS Exception: null is not an object (evaluating 'this.onDonePressList')渲染单元格时,我在编译时得到错误.
如果我直接把console.log放在这样:
<ChildCell onDonePress={() => console.log('Done pressed in list view')} />
Run Code Online (Sandbox Code Playgroud)
它记录消息很好.
如果我像原来一样离开它:
<ChildCell onDonePress={() => this.onDonePressList()} />
Run Code Online (Sandbox Code Playgroud)
它在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 = {...};
}
Run Code Online (Sandbox Code Playgroud)
但它给了我这个错误:null is not an object (evaluating 'this.onDonePressList')并且不会运行.
更新3: 这是一个反应原生操场的链接
尝试调用onDonePress的pressHandler是这样的:
pressHandler() {
this.props.onDonePress()
}
Run Code Online (Sandbox Code Playgroud)
另外,绑定this到您renderRow和renderSectionHeader:
<ListView
dataSource={this.state.dataSource}
style={styles.listView}
renderRow={this.renderCell.bind(this)}
renderSectionHeader={this.renderSectionHeader.bind(this)}
/>
Run Code Online (Sandbox Code Playgroud)
我在这里使用上面的函数设置了一个例子.
https://rnplay.org/apps/DcdAuw
| 归档时间: |
|
| 查看次数: |
9335 次 |
| 最近记录: |