admin管理员组文章数量:1392116
I can't seem to figure out why I am not able to set the default value for react-bootstrap switch to false (off). It seems the only time the value will change is when I trigger the onChange event handler. Am I missing something? Here is the switch portion in my form:
<Form.Group as={Row} className="mb-3">
<Col sm={10}>
<Form.Check
type="switch"
id="custom-switch"
label="Enable GTC"
defaultChecked="false"
onChange={(e) => setField('gtc', e.target.checked)}
/>
</Col>
</Form.Group>
Here is how I am handling the state for the form.
const setField = (field, value) => {
setForm({
...form,
[field]: value,
});
};
I would think `defaultChecked="false" would do the trick but it does not.
Thanks!
I can't seem to figure out why I am not able to set the default value for react-bootstrap switch to false (off). It seems the only time the value will change is when I trigger the onChange event handler. Am I missing something? Here is the switch portion in my form:
<Form.Group as={Row} className="mb-3">
<Col sm={10}>
<Form.Check
type="switch"
id="custom-switch"
label="Enable GTC"
defaultChecked="false"
onChange={(e) => setField('gtc', e.target.checked)}
/>
</Col>
</Form.Group>
Here is how I am handling the state for the form.
const setField = (field, value) => {
setForm({
...form,
[field]: value,
});
};
I would think `defaultChecked="false" would do the trick but it does not.
Thanks!
Share Improve this question edited Dec 22, 2022 at 20:45 Yilmaz 50.1k18 gold badges218 silver badges271 bronze badges asked Jan 14, 2022 at 22:43 rf guyrf guy 4392 gold badges11 silver badges29 bronze badges 03 Answers
Reset to default 3First
const [switchState, setSwitchState] = useState(false);
then assign the :
defaultChecked={switchState}
Now write the change handler function
const handleChange=(e)=>{
setField('gtc', e.target.checked)
setSwitchState(!switchState)
}
final code:
<Form.Group as={Row} className="mb-3">
<Col sm={10}>
<Form.Check
type="switch"
id="custom-switch"
label="Enable GTC"
defaultChecked={switchState}
onChange={handleChange}
/>
</Col>
</Form.Group>
Remove defaultChecked="false"
. By having it as a prop, defaultChecked
is set to true.
Use defaultChecked={false}
instead. The value should be a boolean, rather than a string.
However, the answer posted by @Yilmaz is the full solution.
本文标签: javascriptreactbootstrap form switch buttonStack Overflow
版权声明:本文标题:javascript - react-bootstrap form switch button - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744762353a2623826.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论