我有麻烦更新复选框的状态后,它被分配的默认值checked=“checked”在React。
var rCheck = React.createElement('input',
{
type: 'checkbox',
checked: 'checked',
value: true
}, 'Check here');
在分配checked="checked"后,我无法通过单击取消选中/选中来交互复选框状态。
我有麻烦更新复选框的状态后,它被分配的默认值checked=“checked”在React。
var rCheck = React.createElement('input',
{
type: 'checkbox',
checked: 'checked',
value: true
}, 'Check here');
在分配checked="checked"后,我无法通过单击取消选中/选中来交互复选框状态。
当前回答
你可以使用一个状态变量"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 });
}
我知道这是对一个老问题的晚回复,但这个简短的解决方案可能会帮助其他用户。
其他回答
除了正确答案,你还可以这样做:P
<input name="remember" type="checkbox" defaultChecked/>
如果该复选框仅与React一起创建。createElement然后属性 使用defaultChecked。
React.createElement('input',{type: 'checkbox', defaultChecked: false});
归功于@nash_ag
您可以将"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>
要与复选框交互,您需要在更改复选框后更新复选框的状态。你可以使用defaultChecked来设置默认值。
一个例子:
<input type="checkbox" defaultChecked={this.state.chkbox} onChange={this.handleChangeChk} />
你可以使用一个状态变量"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 });
}
我知道这是对一个老问题的晚回复,但这个简短的解决方案可能会帮助其他用户。