组件正在文本类型的不受控制的输入更改为 ReactJS 的受控错误
问题说明
警告:组件正在更改要控制的文本类型的不受控制的输入.输入元素不应从不受控切换到受控(反之亦然).在组件的生命周期内决定使用受控输入元素还是不受控输入元素.*
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.*
以下是我的代码:
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>
)
}
正确答案
原因是,在你定义的状态下:
The reason is, in state you defined:
this.state = { fields: {} }
fields 作为一个空白对象,所以在第一次渲染时,this.state.fields.name
将是 undefined
,并且输入字段将得到它的值:
fields as a blank object, so during the first rendering this.state.fields.name
will be undefined
, and the input field will get its value as:
value={undefined}
因此,输入字段将变得不受控制.
Because of that, the input field will become uncontrolled.
在输入中输入任何值后,状态中的 fields
将更改为:
Once you enter any value in input, fields
in state gets changed to:
this.state = { fields: {name: 'xyz'} }
此时输入字段被转换为受控组件;这就是您收到错误的原因:
And at that time the input field gets converted into a controlled component; that's why you are getting the error:
组件正在将文本类型的不受控制的输入更改为控制.
A component is changing an uncontrolled input of type text to be controlled.
可能的解决方案:
1- 将状态中的 fields
定义为:
1- Define the fields
in state as:
this.state = { fields: {name: ''} }
2- 或者使用 短路评估像这样:
2- Or define the value property by using Short-circuit evaluation like this:
value={this.state.fields.name || ''} // (undefined || '') = ''
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tangcbjge
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
检查邮件是否发送成功
it1352 07-25 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20