【发布时间】:2016-09-11 17:55:24
【问题描述】:
我在父 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>
);
}
}
提前致谢!
【问题讨论】:
标签: listview react-native components parent-child state