报错信息:
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
在 React 框架中会报这样的错误,界面效果如下:
问题原因:
如果value值为undefined则会报如上警告,解决方法:
问题原因:React 中受控组件和非受控组件的问题。
源代码是这样的(JSX):
<FormGroup>
<Label for="fileName">{gettext('Name')}</Label>
<Input
id="fileName"
onKeyPress={this.handleKeyPress}
innerRef={input => {this.newInput = input;}}
value={this.state.childName}
onChange={this.handleChange}
/>
</FormGroup>
这个组件中 value = {this.state.childName} 有一些情况是 this.state.childName === undefined 那么这个组件就会变成非受控组件。
解决方案: value = { this.state.childName || ‘’ } 如果当前的状态是 undefined 那么组件的值是空字符串。
补充: 非受控组件和受控组件:在 react 中,Input textarea 等组件默认是不受控值的(输入框内部的值是用户控制,和React无关)。但是这里可以转化成受控组件,就是通过 onChange 事件获取当前输入内容,将当前输入内容作为 value 传入,此时就成为受控组件。好处:可以通过 onChange 事件控制用户输入,使用正则表达式过滤不合理输入。