React Native - CheckBox unable to uncheck the “checked” box

依然范特西╮ 提交于 2020-04-30 16:34:56

问题


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.

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.

So, my goal is to make a CheckBox that can check(ofcourse) and also uncheck, if ever a user mischeck or mistap a CheckBox.

Here's my code

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:


Method 1: Make check an object

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/>
    )
}
}

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



来源:https://stackoverflow.com/questions/54111540/react-native-checkbox-unable-to-uncheck-the-checked-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!