Conclusion: Radio and checkbox are controlled by operating Checked, and value only plays an auxiliary role.

I don’t have to say a word. Get right to the code.

Radio buttons

/ / HTML
( <input type="radio" name="" id="" value="finish" 
checked={this.state.radioValue= = ='finish'} 
onChange={this.handleChange} />
<input type="radio" name="" id="" value="unfinish" 
checked={this.state.radioValue= = ='unfinish'} 
onChange={this.handleChange} /> )

// state
state = {
    radioValue: 'finish'
}

/ / change event
handleChange = (event) = > {
    this.setState({
        radioValue: event.target.value
    });
};
Copy the code

Check box

/ / HTML
( <input type="checkbox" name="" id="" value='eat'
checked={this.state.checkboxArr.indexOf('Eat ') >= 0? True: false} onChange={this.handelchange. Bind (this, 'feed ')} />
<input type="checkbox" name="" id="" value='sleep'
checked={this.state.checkboxArr.indexOf('Sleep ') >= 0? True: false} onChange={this.handelchange. Bind (this, 'sleep ')} />
<input type="checkbox" name="" id="" value='Beat the beans'
checked={this.state.checkboxArr.indexOf(> < span style = "box-sizing: border-box;= 0? } onChange={this.handelchange. Bind (this, 'handelChange ')} /> )
OnChange ={handelChange}
// Accordingly, inside the change event function
// Use event.target.value to get the option clicked by the user (like the radio event function above)

// state
state = {
    newCheckboxArr: ['eat'.'sleep']}/ / change event
handelChange = (value, event) = > {
    let newCheckboxArr = [...this.state.checkboxArr]
    if (newCheckboxArr.indexOf(value) >= 0) {
        // If selected, the option is removed from the array
        newCheckboxArr.splice(newCheckboxArr.indexOf(value), 1)}else {
        // If it is selected, add it
        newCheckboxArr.push(value);
    }
    / / update the state
    this.setState({ checkboxArr: newCheckboxArr })
}
Copy the code

Some meaningless analysis can be ignored

React: Input, SELECT, and textarea are controlled by value. After all, their value property values are directly or indirectly displayed in the view;

But what the radio and the checkbox show in the view is only one icon that is checked or not, and that status has nothing to do with the checked property, not the value.

Therefore, the only way to implement controlled radio and checkbox is to work with checked properties.