在 React Native 中使用多个复选框处理状态
Handling state with multiple checkboxes in React Native
我有一个带有两个复选框的简单表格,供某人选择一个或另一个,即 Yes
或 No
,但不能同时选择两者。我正在使用 React-native-element
工具包,如下所示。
export default class CheckerForm extends React.Component {
state = {
checked: false,
}
handleYesCheck =() => {
this.setState({checked: !this.state.checked})
}
handleNoCheck =() => {
this.setState({checked: !this.state.checked})
}
render(){
const { checked } = this.state
return (
<View>
<CheckBox
center
title='Yes'
checked={checked}
onPress={this.handleYesCheck}
/>
<CheckBox
center
title='No'
checked={checked}
onPress={this.handleNoCheck}
/>
<View>
我想捕获和修改复选框的状态,但是当我单击其中一个复选框时,我修改了另一个复选框的状态,即两者都将被选中和取消选中。我如何独立修改复选框的状态,以便当我单击 Yes
时,No
未选中,反之亦然?一般来说,捕获状态以便我可以使用它的最佳方法是什么。
你可以做的是有一个复选框数组,并在状态中保存选中的索引。
state = {
checkedId: -1,
checkboxes: [{
id: "yes",
title: "Yes"
}, {
id: "no",
title: "No"
}]
}
handleCheck = (checkedId) => {
this.setState({
checkedId
})
}
render() {
const {
checkboxes,
checkedId
} = this.state
return ( <
View > {
checkboxes.map(checkbox => ( <
CheckBox center key = {
checkbox.id
}
title = {
checkbox.title
}
checked = {
checkbox.id == checkedId
}
onPress = {
() => this.handleCheck(checkbox.id)
}
/>
)
} <
View >
)
}
这样你也可以处理两个以上的复选框,并且还知道索引选中了哪个。
我有一个带有两个复选框的简单表格,供某人选择一个或另一个,即 Yes
或 No
,但不能同时选择两者。我正在使用 React-native-element
工具包,如下所示。
export default class CheckerForm extends React.Component {
state = {
checked: false,
}
handleYesCheck =() => {
this.setState({checked: !this.state.checked})
}
handleNoCheck =() => {
this.setState({checked: !this.state.checked})
}
render(){
const { checked } = this.state
return (
<View>
<CheckBox
center
title='Yes'
checked={checked}
onPress={this.handleYesCheck}
/>
<CheckBox
center
title='No'
checked={checked}
onPress={this.handleNoCheck}
/>
<View>
我想捕获和修改复选框的状态,但是当我单击其中一个复选框时,我修改了另一个复选框的状态,即两者都将被选中和取消选中。我如何独立修改复选框的状态,以便当我单击 Yes
时,No
未选中,反之亦然?一般来说,捕获状态以便我可以使用它的最佳方法是什么。
你可以做的是有一个复选框数组,并在状态中保存选中的索引。
state = {
checkedId: -1,
checkboxes: [{
id: "yes",
title: "Yes"
}, {
id: "no",
title: "No"
}]
}
handleCheck = (checkedId) => {
this.setState({
checkedId
})
}
render() {
const {
checkboxes,
checkedId
} = this.state
return ( <
View > {
checkboxes.map(checkbox => ( <
CheckBox center key = {
checkbox.id
}
title = {
checkbox.title
}
checked = {
checkbox.id == checkedId
}
onPress = {
() => this.handleCheck(checkbox.id)
}
/>
)
} <
View >
)
}
这样你也可以处理两个以上的复选框,并且还知道索引选中了哪个。