状态本身会切换,但UI不会。
该对象如下所示:
data: [ {id: 0, key: 'Key1', checked: false }, ... }]
我在实施中遗漏了什么?
onCheckBoxChange(id) {
let arr = Array.from(Object.create(this.state.data));
arr[id].checked = !arr[id].checked;
this.setState({
data: arr
})
}
render() {
return (
<Container>
<Content>
<List dataArray={this.state.data}
renderRow={(item) =>
<View>
<ListItem>
<CheckBox checked={ this.state.data[item.id].checked }
onPress={()=> this.onCheckBoxChange(item.id)}/>
<Text>{item.key}</Text>
</ListItem>
</View>
}>
</List>
</Content>
</Container>
)
}
}
答案 0 :(得分:1)
我相信你正在改变状态,你也正在使用id来确定索引。试试这个:
onCheckBoxChange(index) {
const arr = [...this.state.data];
const newItem = {
...arr[index],
checked: !arr[index].checked,
};
arr[index] = newItem;
this.setState({
data: arr
})
}
render() {
return (
<Container>
<Content>
<List dataArray={this.state.data}
renderRow={(item, index) => // use index instead of id
<View>
<ListItem> // you already have the item so dont need to go check from state
<CheckBox checked={ item.checked }
onPress={()=> this.onCheckBoxChange(index)}/>
<Text>{item.key}</Text>
</ListItem>
</View>
}>
</List>
</Content>
</Container>
)
}
}