uncheck checkbox programmatically in reactjs

2020-08-09 10:07发布

问题:

I am messing with checkboxes and I want to know that is there a way in which I can uncheck a checkbox on click of a button by calling a function?? If so? How can I do that?

<input type="checkbox" className="checkbox"/>
<button onClick={()=>this.unCheck()}

How can I uncheck the checkbox programmatically and what if I have multiple checkboxes generated dynamically using map function. How can I uncheck them If I want to?

回答1:

There is property of checkbox checked you can use that to toggle the status of check box.

Possible Ways:

1- You can use ref with check boxes, and onClick of button, by using ref you can unCheck the box.

2- You can use controlled element, means store the status of check box inside a state variable and update that when button clicked.

Check this example by using ref, assign a unique ref to each check box then pass the index of that item inside onClick function, use that index to toggle specific checkBox:

class App extends React.Component{

   constructor(){
      super();
      this.state = {value: ''}
   }
   
   unCheck(i){
      let ref = 'ref_' + i;
      this.refs[ref].checked = !this.refs[ref].checked;
   }
   
   render(){
     return (
       <div>
        {[1,2,3,4,5].map((item,i) => {
           return (
              <div>
                 <input type="checkbox" checked={true} ref={'ref_' + i}/>
                 <button onClick={()=>this.unCheck(i)}>Toggle</button>
              </div>
            )
        })}      
       </div>
     )
   }

}

ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>

Check this example of controlled element, means storing the state of checkbox inside state variable, and on click of button change the value of that:

class App extends React.Component{

   constructor(){
      super();
      this.state = {value: []}
   }
   
   onChange(e, i){
      let value = this.state.value.slice();
      value[i] = e.target.checked;
      this.setState({value})
   }
       
   unCheck(i){
      let value = this.state.value.slice();
      value[i] = !value[i];
      this.setState({value})
   }
       
   render(){
     return (
        <div>
           {[1,2,3,4,5].map((item,i) => {
             return (
                <div>
                  <input checked={this.state.value[i]} type="checkbox" onChange={(e) => this.onChange(e, i)}/>
                  <button onClick={()=>this.unCheck(i)}>Toggle</button>
                </div>
              )
           })}      
         </div>
       )
    }
}

ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>



回答2:

React

Checked

  1. Using State
     <input type="radio" name="count" value="minus" onChange={this.handleRadioChange} checked={this.state.operation == "minus"} /> Decrement

2.Using Refs

<input type="radio" name="count" ref="minus" /> Decrement
onSubmit(e){ this.refs.minus.checked = false }


回答3:

Using plain javascript you can acheive like below.

 function unCheck() {
   var x = document.getElementsByClassName("checkbox");
   for(i=0; i<=x.length; i++) {
      x[i].checked = false;
    }   
 }

Small DEMO



回答4:

I was thinking of a thing like that:

<input onChange={(input) => this.onFilterChange(input)} className="form-check-input" type="checkbox" />

onFilterChange = (input) => { let { value, checked } = input.target;}

unCkeckAll = () => {
    [...document.querySelectorAll('.form-check-input')].map((input) => {
        if (input.checked) {
            let fakeInput = {
                target: {
                    value: input.value,
                    checked: false
                }
            }
            input.checked = !input.checked;
            this.onFilterChange(fakeInput);
        }
        return null;
    })
}


回答5:

Checkboxes have a checked property, you can hook it to the state and change it dynamically. Check these links:

https://facebook.github.io/react/docs/forms.html#handling-multiple-inputs

http://react.tips/checkboxes-in-react/