警告:一个组件正在将不受控制的输入更改为受控制的输入。这可能是由于值从未定义更改为已定义值引起的。
Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value.
ID: react/controlled-uncontrolled-input-switch
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| [email protected] | active | — | — | — |
| [email protected] | active | — | — | — |
根因分析
输入元素的 value 属性在重新渲染期间从未定义(不受控制)变为已定义值(受控制),或反之,导致 React 意外切换模式。
English
An input element's value prop transitions from undefined (uncontrolled) to a defined value (controlled) or vice versa during a re-render, causing React to switch modes unexpectedly.
官方文档
https://react.dev/reference/react-dom/components/input#controlling-an-input-with-a-state-variable解决方案
-
Initialize the state variable to an empty string instead of undefined, and always pass a string to the value prop.
-
If the value can legitimately be null/undefined, use defaultValue for the initial uncontrolled state and then switch to controlled with a key prop to remount the input.
无效尝试
常见但无效的做法:
-
Adding a default value to the input via defaultValue prop while keeping value undefined
85% 失败
defaultValue is only for uncontrolled inputs; mixing it with a value prop that later becomes defined still triggers the warning.
-
Using a ternary operator to conditionally set value to undefined or a string
90% 失败
This creates the exact flip-flop between undefined and defined that causes the warning.
-
Setting the input's value to an empty string by default to avoid undefined
40% 失败
While this avoids the warning, it may not reflect the intended initial state (e.g., null for optional fields), leading to incorrect UX.