我在控制台中不断收到此错误:
warning.js?8a56:36警告:LoginForm正在更改受控输入
密码类型不受控制。输入元素不应切换
从受控变为非受控(反之亦然)。确定使用之间
受控制或不受控制的输入元素
零件。更多信息:https://facebook.github.io/react/docs/forms.html#controlled-components
我看过这些问题:
How to create a controlled input with empty default in React 15-我已经定义了我的状态
React Controlled vs Uncontrolled inputs-我的函数接受一个事件而不是一个密码参数
React - changing an uncontrolled input-我已经将密码定义为空
这是组件:
export default class LoginForm extends Component {
constructor(props) {
super(props);
this.state = {
values: {
username: "",
password: ""
}
};
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this._clearInput = this._clearInput.bind(this);
}
onSubmit(event) {
// this.props.attemptLogin
event.preventDefault();
console.log(this.state.values);
let {username, password} = this.state.values;
this.props.attemptLogin(username, password)
.then((userInfo) => {
console.log(userInfo);
LocalStore.setJson('api', userInfo.api);
LocalStore.setJson('user', userInfo.user);
this._clearInput('username' , 'password');
})
.catch((err) => {
console.log("Failed:");
console.log(err);
this._clearInput('password');
});
}
_clearInput(...fields) {
let newValuesState = {};
fields.forEach((field) => {
newValuesState[field] = '';
});
this.setState({values: newValuesState});
}
onChange(event) {
let name = event.target.name;
let value = event.target.value;
this.setState({values: {[name]: value}});
}
render() {
return (
<div>
<form method="post" onSubmit={this.onSubmit}>
<div><input type="text" name="username" onChange={this.onChange} value={this.state.values.username}/></div>
<div><input type="password" name="password" onChange={this.onChange} value={this.state.values.password}/></div>
<div><button type="submit">Login</button></div>
</form>
</div>
);
}
}
LoginForm.propTypes = {
attemptLogin: React.PropTypes.func.isRequired
};
该代码似乎确实起作用,但是该错误在控制台中弹出,因此我无法继续操作,直到我停止出现它为止。谁能看到我在组件中做错了什么?
最佳答案
由于您要在state.values
中嵌套值,因此onChange
函数将删除未更改的字段。您可以改为执行以下操作:
onChange(event) {
let name = event.target.name;
let value = event.target.value;
let values = {...this.state.values};
values[name] = value;
this.setState({values}});
}