React Bootstrap中有一个复选框输入。如果我的变量isTrue=true
要设置为checked。
我正在将checked ={isTrue ? true : false}
添加到输入中,但完成此操作后,我无法取消选中它
<input type='checkbox' checked ={isTrue ? true : false} />
当我这样做时:
<input type="checkbox" {checked ? 'checked' : ''} name="example" />
我得到错误:";排列类型只能由对象类型创建;
如何有条件地将checked
设置为复选框输入?
当isTrue
发生变化(从false变为true(时,您将需要运行useEffect
。因此,它将更改绑定到复选框的状态变量的值:
const { useEffect, useState } = React;
function App() {
const [isTrue, setIsTrue] = useState(false);
const [checkBoxValue, setCheckBoxValue] = useState(false);
const onButtonClick = () => {
setIsTrue((curr) => !curr);
};
useEffect(() => {
if (!isTrue) return;
setCheckBoxValue(true);
}, [isTrue]);
return (
<div className="App">
<p>IsTrue: {isTrue.toString()}</p>
<p>CheckBox value: {checkBoxValue.toString()}</p>
<button type="button" onClick={onButtonClick}>
Toggle isTrue
</button>
<input
type="checkbox"
onChange={() => setCheckBoxValue((curr) => !curr)}
checked={checkBoxValue}
/>
</div>
);
}
ReactDOM.createRoot(
document.getElementById("root")
).render(
<App />
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
<div id="root"></div>
我添加了这个并成功了。
<input type="checkbox" name="example" {...(isTrue && { checked: true })} />
您可以
<input type='checkbox' checked ={isTrue} onClick={handleChange} />
并创建处理onClick的函数,并相应地更改isTrue