【发布时间】:2020-07-11 16:36:17
【问题描述】:
我有一个函数组件,假设变量是:
const [currentValue, setCurrentValue] = useState(false);
我有一个这样的复选框:
<label for='checking'><input type="checkbox" id="checking" checked={currentValue ? true : false} onChange={e => handleChecking(e)} />
然后我有一个函数:
const handleChecking = (e) => {
setCurrentValue(e.target.checked);
console.log(currentValue);
}
现在的问题是,即使复选框按预期运行,console.log 显示的值也不正确。
当复选框为真时,它显示我为假。 当复选框为假时,它显示为真。
目前在函数中似乎没有更新状态,但在复选框本身上按预期工作。
为了更直白,输出如下:
console.log(e.target.checked);
setCurrentValue(e.target.checked);
console.log(currentValue);
是:
当复选框为真时:
true
false
当它为假时:
false
true
【问题讨论】:
-
为什么你检查的属性不是
checked={currentValue} -
我只是简化了这个例子,是的,我们可以在这个例子中使用
checked={currentValue},但我仍然面临这个问题。
标签: reactjs