我有一个选项列表,其中包含复选框和父按钮ListView
中的完成按钮。当完成按钮被按下时,我想知道哪个复选框被选中。如何使用React-Native获得父级ListView组件中子复选框组件的状态?
我应该补充一点,我尝试使用ChildCheckBox
的回调函数来维护ListView
中的选中框的数组。它工作正常,除非导航回到ListView
,阵列将被重置,而复选框仍然出现在检查。我宁愿让onDonePress()
函数只是查询哪些框被检查,然后在那个时候作出相应的响应,而不是依赖维护一个数组的ListView
。
这里是ListView
:
class ParentListView extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
};
}
componentDidMount() {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(ROW_DATA),
});
}
onCheckPress() {
console.log('Check Pressed')
// callback from ChildCheckBoxCell...?
}
onDonePress() {
console.log('Done pressed')
// callback from ChildDoneCell...?
}
render() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow.bind(this)}
style={styles.listView}
/>
);
}
renderRow(cell) {
if (cell.type === 'ChildCheckBoxCell') {
return (
<ChildCheckBoxCell onChange={() => this.onCheckPress()} />
);
}
if (cell.type === 'ChildDoneCell') {
return (
<ChildDoneCell onDonePress={() => this.onDonePress()}/>
);
}
}
}
这里是ChildCheckBoxCell
组件:
class ChildCheckBoxCell extends Component {
constructor(props) {
super(props);
this.state = {
isChecked: false,
};
}
onChange() {
this.setState({isChecked: !this.state.isChecked});
//Callback...
this.props.onChange();
}
render() {
return (
<TouchableHighlight onPress={() => this.onChange()}>
<Text>{this.state.isChecked? 'Checked' : 'UnChecked'}</Text>
</TouchableHighlight>
);
}
}
最后,这里是ChildDoneCell
组件
class ChildDoneCell extends Component {
onDonePress() {
//Callback...
this.props.onDonePress();
}
render() {
return (
<TouchableHighlight onPress={() => this.onDonePress()}>
<Text>DONE</Text>
</TouchableHighlight>
);
}
}
提前感谢!
感谢您的非常详细的答案!我刚刚尝试过实现它,出于某种原因,CheckboxCell不响应listView中所做的更改。在第1步中,我有'cell.isChecked =!cell.isChecked',但组件并不响应这些更改。另外,'ComponentWillReceiveProps()'不会在'CheckBoxCell'中被调用。 –
更新数据源时,必须使用cloneWithRows。你是否熟悉它? – rclai
缺失的链接是我没有更新数据源,我现在就试试,谢谢 –