React Native-CheckBox无法取消选中“已检查”框 [英] React Native - CheckBox unable to uncheck the "checked" box
问题描述
我已经使用React本机一个月了,但这是我第一次在应用程序中使用 CheckBox 。因此,最近我一直在努力检查 Flatlist 中的特定复选框,但现在可以了。
I've been using React native for a month now but it's my first time to use a CheckBox in my application. So, lately I've been struggling to check a specific checkbox inside a Flatlist but now I can.
但是在测试我的复选框后,我确实请注意,一旦我检查了一个特定的CheckBox(或多个复选框),它就不会取消检查。
But upon testing my checkboxs I did notice that once I check a specific a CheckBox(or more than 1 checkbox) it doesn't UNCHECK.
所以,我的目标是制作一个可以选中(当然)并且也可以取消选中的CheckBox,如果用户错失或误用了CheckBox。
So, my goal is to make a CheckBox that can check(ofcourse) and also uncheck, if ever a user mischeck or mistap a CheckBox.
这是我的代码
export default class tables extends Component {
constructor(props){
super(props)
this.state = {
...
check: false
}
}
checkBox_Test = (item, index) => {
let { check } = this.state;
check[index] = !check[index];
this.setState({ check: check })
alert("now the value is " + !this.state.check);
alert("now the value is " + item.tbl_id);
console.log(item.tbl_id)
}
render() {
return(
<View>
....
<Flatlist
....
<CheckBox
value = { this.state.check }
onChange = {() => this.checkBox_Test(item) }
/>
....
/>
<View/>
)
}
}
推荐答案
方法1:检查对象
export default class tables extends Component {
constructor(props){
super(props)
this.state = {
...
check: {}
}
}
checkBox_Test = (id) => {
const checkCopy = {...this.state.check}
if (checkCopy[id]) checkCopy[id] = false;
else checkCopy[id] = true;
this.setState({ check: checkCopy });
}
render() {
return(
<View>
....
<Flatlist
....
<CheckBox
value = { this.state.check[item.tbl_id] }
onChange = {() => this.checkBox_Test(item.tbl_id) }
/>
....
/>
<View/>
)
}
}
方法2:为每个FlatList项目制作一个单独的项目
Method 2: Make a separate item for each FlatList item
class ListItem extends Component {
constructor(props){
super(props)
this.state = {
...
check: false
}
}
checkBox_Test = (id) => {
this.setState((prevState) => ({ check: !prevState.check }));
}
render() {
return(
<View>
<CheckBox
value = { this.state.check }
onChange = { this.checkBox_Test }
/>
</View>
)
}
}
让我知道它是否对您有用
Let me know if it works for you
这篇关于React Native-CheckBox无法取消选中“已检查”框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!