[英]Email Input Warning - A component is changing a controlled input of type text to be uncontrolled
In my React app, I'm getting this error during onChange event with my email input field: 在我的React应用程序中,我的电子邮件输入字段在onChange事件期间收到此错误:
Warning: A component is changing a controlled input of type text to be uncontrolled.
警告:组件正在将文本类型的受控输入更改为不受控制。 Input elements should not switch from controlled to uncontrolled (or vice versa).
输入元素不应从受控状态切换到非受控状态(反之亦然)。
Here's the onChange block that's causing this warning; 这是导致此警告的onChange块; The error goes away if I remove the first if block but of course I need it there for email validation.
如果我删除了第一个if块,该错误就会消失,但是我当然需要在那里进行电子邮件验证。
validateEmail(email) {
const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
handleOnChange = e => {
const { name, value } = e.target;
const emailInput = e.target.value;
const emailValid = this.validateEmail(emailInput);
if (name === 'email') {
this.setState({
inputs: {
email: emailInput,
},
errors: {
email: !emailValid,
},
});
} else {
this.setState({
inputs: {
...this.state.inputs,
[name]: value,
},
errors: {
...this.state.errors,
[name]: false,
},
});
}
};
State: 州:
constructor() {
super();
this.state = {
inputs: {
name: '',
email: '',
message: '',
},
phone: '',
show: true,
errors: {
name: false,
email: false,
message: false,
},
};
}
How do I keep my current code and address the warning? 如何保留当前代码并解决警告?
You need to spread the existing/previous state in the if-block. 您需要在if块中散布现有/先前状态。 You likely have other
input
tags that were initially connected to the input-state
object which looks like: 您可能还有其他最初连接到
input-state
对象的input
标签,如下所示:
inputs: {
name: "",
email: "",
message: ""
}
<input value={this.state.input.name} name="name"/>
<input value={this.state.input.email} name="email"/>
<input value={this.state.input.message} name="message"/>
but when you used this.setState()
in your posted code, the connection is lost. 但是当您在已发布的代码中使用
this.setState()
时,连接将丢失。 You are setting the inputs
state to an object with a single property of email : 您正在将
inputs
状态设置为具有单个属性email的对象:
inputs: {
email: "valueFromEventTarget"
}
What you need to do is spread the existing state so you don't lose the other key/value pairs in the input object: Update your handleChange()
function to this: 您需要做的是散布现有状态,以免丢失输入对象中的其他键/值对:将
handleChange()
函数更新为此:
handleOnChange = e => {
const { name, value } = e.target;
const emailInput = e.target.value;
const emailValid = this.validateEmail(emailInput);
if (name === 'email') {
this.setState({
inputs: {
...this.state.inputs,
email: emailInput,
},
errors: {
...this.state.errors,
email: !emailValid,
},
});
} else {
this.setState({
inputs: {
...this.state.inputs,
[name]: value,
},
errors: {
...this.state.errors,
[name]: false,
},
});
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.