React - 改变一个不受控制的输入
我有一个简单的反应组件,我认为它有一个受控输入的表单:
I have a simple react component with the form which I believe to have one controlled input:
import React from 'react';
export default class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
render() {
return (
<form className="add-support-staff-form">
<input name="name" type="text" value={this.state.name} onChange={this.onFieldChange('name').bind(this)}/>
</form>
)
}
onFieldChange(fieldName) {
return function (event) {
this.setState({[fieldName]: event.target.value});
}
}
}
export default MyForm;
当我运行我的应用程序时,我收到以下警告:
When I run my application I get the following warning:
警告:MyForm 正在将文本类型的不受控制的输入更改为受控.输入元素不应从不受控制切换到控制(反之亦然).决定使用受控或组件生命周期内不受控制的输入元素
Warning: MyForm 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
我相信我的输入是受控的,因为它具有价值.我想知道我做错了什么?
I believe my input is controlled since it has a value. I am wondering what am I doing wrong?
我正在使用 React 15.1.0
I am using React 15.1.0
推荐答案
我相信我的输入是受控的,因为它有一个值.
I believe my input is controlled since it has a value.
对于要控制的输入,它的值必须与状态变量的值相对应.
For an input to be controlled, its value must correspond to that of a state variable.
您的示例中最初未满足该条件,因为最初未设置 this.state.name
.因此,输入最初是不受控制的.一旦第一次触发 onChange
处理程序,就会设置 this.state.name
.此时,满足上述条件,认为输入受控.这种从不受控到受控的转变会产生上述错误.
That condition is not initially met in your example because this.state.name
is not initially set. Therefore, the input is initially uncontrolled. Once the onChange
handler is triggered for the first time, this.state.name
gets set. At that point, the above condition is satisfied and the input is considered to be controlled. This transition from uncontrolled to controlled produces the error seen above.
通过在构造函数中初始化this.state.name
:
By initializing this.state.name
in the constructor:
例如
this.state = { name: '' };
输入将从一开始就受到控制,从而解决问题.有关更多示例,请参阅 React Controlled Components.
the input will be controlled from the start, fixing the issue. See React Controlled Components for more examples.
与此错误无关,您应该只有一个默认导出.你上面的代码有两个.
Unrelated to this error, you should only have one default export. Your code above has two.
相关文章