https://codesandbox.io/s/rwm5x1w9r4
我在上面的codesandbox中有一个demo。第一个复选框将所有状态更改为 checked=true
第二个和第三个复选框仅管理它们自己的状态。状态更改工作正常,但复选框视觉效果没有改变。我必须做什么才能确保复选框根据状态变化运行?
最佳答案
如果你检查控制台,你会看到一个警告:
Warning: A component is changing an uncontrolled input of type checkbox to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.
您看到此问题是因为您没有从一开始就控制其他两个复选框的状态,而是稍后尝试自己管理它。
// but you are not initializing the checkbox ids "1" & "2", so they are uncontrolled.
state = {
"checkboxA" : true,
"checkboxB" : true,
"checkboxC" : true
}
幕后发生的事情是:不受控制的组件的状态由 dom 维护,即在 react 范围之外。稍后当您要求 react 以控制状态时, react 不确定什么是正确的行为并退出。
您可以通过将其他两个复选框设置为状态来明确要求对控制使用react来更正它。
state = {
"checkboxA" : true,
"1" : true,
"2" : true
}
这里是 controlled 文档的链接和 uncontrolled React 官方文档中的组件。
更新:这是我从你的沙箱中 fork 出来的沙箱:https://mm3379x0ox.codesandbox.io/
关于reactjs - Material Ui 复选框受控状态更改不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55453927/