我有麻烦更新复选框的状态后,它被分配的默认值checked=“checked”在React。

var rCheck = React.createElement('input',
    {
        type: 'checkbox',
        checked: 'checked',
        value: true
    }, 'Check here');

在分配checked="checked"后,我无法通过单击取消选中/选中来交互复选框状态。


当前回答

您可以将"true"或""传递给input复选框的checked属性。空引号("")将被理解为假的,该项将不被选中。

let checked = variable === value ? "true" : "";
<input
     className="form-check-input"
    type="checkbox"
    value={variable}
    id={variable}
    name={variable}
    checked={checked}
/>
<label className="form-check-label">{variable}</label>

其他回答

它的工作

<input type="checkbox" value={props.key} defaultChecked={props.checked} ref={props.key} onChange={this.checkboxHandler} />

函数初始化它

{this.viewCheckbox({ key: 'yourKey', text: 'yourText', checked: this.state.yourKey })}

我尝试使用Class组件来实现这一点: 您可以查看相同的消息

class Checkbox extends React.Component{
constructor(props){
    super(props)
    this.state={
        checked:true
    }
    this.handleCheck=this.handleCheck.bind(this)
}

handleCheck(){
    this.setState({
        checked:!this.state.checked
    })
}

render(){
    var msg=" "
    if(this.state.checked){
        msg="checked!"
    }else{
        msg="not checked!"
    }
    return(
        <div>
            <input type="checkbox" 
            onChange={this.handleCheck}
            defaultChecked={this.state.checked}
            />
            <p>this box is {msg}</p>
        </div>
    )
}

}

取值为true或false defaultChecked={true}

<input type="checkbox"
        defaultChecked={true}
        onChange={() => setChecked(!checked)}
      />

我将状态设置为任何[]类型。并在构造函数中将状态设置为null。

onServiceChange = (e) => {
    const {value} = e.target;
    const index = this.state.services.indexOf(value);
    const services = this.state.services.filter(item => item !== value);
    this.setState(prevState => ({
        services: index === -1 ? prevState.services.push(value) && prevState.services : this.state.services.filter(item => item !== value)
    }))
}

在输入元素中

this.onServiceChange (e)} / > this.onServiceChange (e)} / > this.onServiceChange (e)} / > this.onServiceChange (e)} / >

过了一段时间我才明白。我想这可能对你们都有帮助。

你可以使用一个状态变量"enableSwitch"和一个函数"handleSwitch"来处理你默认的选中Switch:

<div class="custom-control custom-switch">
    <input type="checkbox" class="custom-control-input" id="switchId" checked={this.state.enableSwitch} onClick={this.handleSwitch}/>
    <label class="custom-control-label" for="switchId">switch text</label>
</div>

下面是一个函数,如果用户点击开关,它会反转变量:

handleSwitch = (e) => {
   this.setState({ enableSwitch: !this.state.enableSwitch });
}

我知道这是对一个老问题的晚回复,但这个简短的解决方案可能会帮助其他用户。