这里记录一下React开发过程中遇到的一个Waring及解决方法。
一个Input输入框,当你在输入框中输入时,控制台显示Waring,Console 输出如下:
Warning: A component is changing an uncontrolled input of type text 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. More info: https://fb.me/react-controlled-components
上面报错的意思是:Input 组件从一个非受控组件变成了一个受控组件。
造成这个问题的原因是:初始化时,Input 组件的value
值为undefined
。
所以,要解决该问题,我们只要在初始化时,Input 组件的value
值为undefined
时赋值一个空字符串''
即可。
<Input value={val || ''} onChange={this.handleChange}/>
非受控组件和受控组件的概念可参考:Uncontrolled Components、Controlled Components