组件正在更改ReactJS中要控制的文本类型的不受控制的输入错误 [英] A component is changing an uncontrolled input of type text to be controlled error in ReactJS
问题描述
警告:组件正在更改要控制的文本类型的不受控制的输入。输入元素不应从不受控制切换到受控制(或反之亦然)。决定在组件的生命周期内使用受控或不受控制的输入元素。
我的代码:
constructor(props) {
super(props);
this.state = {
fields: {},
errors: {}
}
this.onSubmit = this.onSubmit.bind(this);
}
....
onChange(field, e){
let fields = this.state.fields;
fields[field] = e.target.value;
this.setState({fields});
}
....
render() {
return(
<div className="form-group">
<input
value={this.state.fields["name"]}
onChange={this.onChange.bind(this, "name")}
className="form-control"
type="text"
refs="name"
placeholder="Name *"
/>
<span style={{color: "red"}}>{this.state.errors["name"]}</span>
</div>
)
}
推荐答案
原因是,在您定义的州:
Reason is, in state you defined:
this.state = { fields: {} }
字段为空白对象,因此在首次渲染时 this.state.fields.name
将为 undefined
,输入字段将获得以下值:
fields as blank object so during first rendering this.state.fields.name
will be undefined
, and input field will get value as:
value={undefined}
因为输入字段将变得不受控制。
Because of that input field will become uncontrolled.
在输入中输入任何值后,状态中的字段
将更改为:
Once you enter any value in input, fields
in state get changed to:
this.state = { fields: {name: 'xyz'} }
此时输入字段会转换为受控组件,这就是您收到错误的原因:
And at that time input field get converted into controlled component, that's why you are getting the error:
组件正在将类型文本的非受控输入更改为
受控制。
A component is changing an uncontrolled input of type text to be controlled.
可能的解决方案:
1-在状态中定义字段
:
this.state = { fields: {name: ''} }
2-或者使用短路评估如下:
value={this.state.fields.name || ''} // (undefined || '') = ''
这篇关于组件正在更改ReactJS中要控制的文本类型的不受控制的输入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!