Warning: A component is changing an uncontrolled input of type text to be controlled 报错分析

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). 

在 React 框架中会报这样的错误,界面效果如下:

问题原因: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} 有一些情况这个是是 undefined 那么这个组件就会变成非受控组件。

解决方案:value = { this.state.childName || '' } 如果当前的状态是 undefined 那么组件的值是空字符串。

补充:非受控组件和受控组件:在 react 中,Input textarea 等组件默认是不受控值的(输入框内部的值是用户控制,和React无关)。但是这里可以转化成受控组件,就是通过 onChange 事件获取当前输入内容,将当前输入内容作为 value 传入,此时就成为受控组件。好处:可以通过 onChange 事件控制用户输入,使用正则表达式过滤不合理输入。

猜你喜欢

转载自blog.csdn.net/weixin_41697143/article/details/89374791