我有麻烦更新复选框的状态后,它被分配的默认值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"后,我无法通过单击取消选中/选中来交互复选框状态。
当前回答
取值为true或false defaultChecked={true}
<input type="checkbox"
defaultChecked={true}
onChange={() => setChecked(!checked)}
/>
其他回答
import React, { useState } from 'react'
const [rememberUser, setRememberUser] = useState(true) //use false for unchecked initially
<input
type="checkbox"
checked={rememberUser}
onChange={() => {
setRememberUser(!rememberUser)
}}
/>
除了正确答案,你还可以这样做:P
<input name="remember" type="checkbox" defaultChecked/>
Don't make it too hard. First, understand a simple example given below. It will be clear to you. In this case, just after pressing the checkbox, we will grab the value from the state(initially it's false), change it to other value(initially it's true) & set the state accordingly. If the checkbox is pressed for the second time, it will do the same process again. Grabbing the value (now it's true), change it(to false) & then set the state accordingly(now it's false again. The code is shared below.
第1部分
state = {
verified: false
} // The verified state is now false
第2部分
verifiedChange = e => {
// e.preventDefault(); It's not needed
const { verified } = e.target;
this.setState({
verified: !this.state.verified // It will make the default state value(false) at Part 1 to true
});
};
第3部分
<form>
<input
type="checkbox"
name="verified"
id="verified"
onChange={this.verifiedChange} // Triggers the function in the Part 2
value={this.state.verified}
/>
<label for="verified">
<small>Verified</small>
</label>
</form>
在我的情况下,我觉得“defaultChecked”不能正常工作的状态/条件。所以我用“checked”和“onChange”来切换状态。
Eg.
checked={this.state.enabled} onChange={this.setState({enabled : !this.state.enabled})}
如果该复选框仅与React一起创建。createElement然后属性 使用defaultChecked。
React.createElement('input',{type: 'checkbox', defaultChecked: false});
归功于@nash_ag