真正的诀窍是在父组件中维护一个选定项目的列表。每个CheckBoxItem 都可以控制自己的状态,但您需要在每次选中/取消选中时将值传递回父组件。
由于您尚未显示您的 CheckBox 组件的来源,我将向您展示如何使用 react-native-elements CheckBox 来实现它。然后可以将这些原则应用于您自己的CheckBox。
这里是App.js
import CheckBoxItem from './CheckBoxItem'
export default class App extends React.Component {
// set some initial values in state
state = {
response: [
{
name:'first'
},
{
name:'second'
},
{
name:'third'
},
{
name:'fourth'
},
{
name:'fifth'
},
{
name:'sixth'
},
],
selectedBoxes: [] // this array will hold the names of the items that were selected
}
onUpdate = (name) => {
this.setState(previous => {
let selectedBoxes = previous.selectedBoxes;
let index = selectedBoxes.indexOf(name) // check to see if the name is already stored in the array
if (index === -1) {
selectedBoxes.push(name) // if it isn't stored add it to the array
} else {
selectedBoxes.splice(index, 1) // if it is stored then remove it from the array
}
return { selectedBoxes }; // save the new selectedBoxes value in state
}, () => console.log(this.state.selectedBoxes)); // check that it has been saved correctly by using the callback function of state
}
render() {
const { response } = this.state;
return (
<View style={styles.container}>
{
response.map(item => <CheckBoxItem label={item.name} onUpdate={this.onUpdate.bind(this,item.name)}/>)
}
</View>
);
}
}
这里是CheckBoxItem
import { CheckBox } from 'react-native-elements'
class CheckBoxItem extends Component<Props> {
state = {
check: false, // by default lets start unchecked
}
onValueChange = () => {
// toggle the state of the checkbox
this.setState(previous => {
return { check: !previous.check }
}, () => this.props.onUpdate());
// once the state has been updated call the onUpdate function
// which will update the selectedBoxes array in the parent componetn
}
render() {
return (
<View>
<CheckBox
title={this.props.label}
checked={this.state.check}
onPress={this.onValueChange}
/>
</View>
);
}
}
export default CheckBoxItem;
说明
创建CheckBoxItem 时,会将两件事传递给它。一个是标签,第二个是onUpdate 函数。 onUpdate 函数将CheckBoxItem 链接回父组件,以便它可以操纵父组件中的状态。
onUpdate 函数在应用此更新之前获取状态的先前值,并查看复选框的名称是否存在于selectedBoxes 数组中。如果它存在于selectedBoxes 数组中,则将其删除,否则将其添加。
现在在您可以访问的父组件中存在一个数组,其中包含所有已选择的项目。
小吃
想试用我的代码吗?好吧,我已经创建了一种小吃,表明它可以工作https://snack.expo.io/@andypandy/checkboxes
设置状态
您可能已经注意到我正在使用setState 做一些不寻常的事情。我确保setState 被正确调用,方法是使用之前的状态值,然后应用我的更新。我还使用setState 在状态更新后进行回调以执行操作的事实。如果您想在此处阅读更多内容,请参阅setState 上的一些精彩文章。