Get the value of checkbox using ref in React

前端 未结 3 889
醉话见心
醉话见心 2020-12-05 17:48

is there any way to get value of checkbox using ref in React. Normal way return always value \"on\" to me.

var MyForm = React.createClass({
    save: functio         


        
相关标签:
3条回答
  • 2020-12-05 18:12

    For checkbox, use "checked" instead of "value":

    var MyForm = React.createClass({
      save: function () {
        console.log(this.refs.check_me.checked);
      },
    
      render: function () {
        return <div><h1>MyForm</h1>
          <div className="checkbox">
            <label>
              <input type="checkbox" ref="check_me" /> Check me out
            </label>
          </div>
          <button className="btn btn-default" onClick={this.save}>Submit</button>
        </div>
      }
    });
    

    As a result:

    0 讨论(0)
  • 2020-12-05 18:12

    There is a classic way to catch the event and corresponding values with the help of:

    event.target.checked, event.target.name
    

    You can see an example:

    class MyForm extends React.Component {
        onChangeFavorite(event){
            console.log(event.target.checked, event.target.name);
        };
        render(){
            return (<div><h1>MyForm</h1>
                <div className="checkbox">
                    <label>
                       <input type="checkbox" name="myCheckBox1" 
                         onChange={this.onChangeFavorite} 
                         defaultChecked={false} /> 
                       Check me out
                    </label>
                </div>
                <button className="btn btn-default" onClick={this.save}>Submit</button>
            </div>)
        };
    };
    
    0 讨论(0)
  • 2020-12-05 18:16

    You can make the checkbox a controlled element by listening to onChange and giving it a state value. Try the following:

    var MyForm = React.createClass({
      save: function(){
        console.log(this.refs.check_me.value);
      },
    
      toggleCheckboxValue: () => {
        this.setState({checkBoxValue: !this.state.checkboxValue});
      },
    
      render: function(){
        return <div><h1>MyForm</h1>
            <div className="checkbox">
                <label>
                    <input type="checkbox" ref="check_me" value={this.state.checkboxValue} onChange={this.toggleCheckboxValue} /> Check me out
                </label>
            </div>
            <button className="btn btn-default" onClick={this.save}>Submit</button>
        </div>
      }
    });
    

    whenever the checkbox is clicked it will run the toggleCheckboxValue function, which will toggle the value of this.state.checkboxValue.

    Just don't forget to initialize the this.state.checkboxValue function in your code.

    Note: As ivarni pointed out, you may want to control the checked value specifically for checkboxes rather than value. Though both solutions will work.

    0 讨论(0)
提交回复
热议问题