【发布时间】:2017-06-19 05:37:38
【问题描述】:
我的控制台中不断出现此错误:
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
};
代码似乎确实有效,但控制台中会弹出此错误,所以我无法继续,直到我让它停止出现。谁能看到我在组件中做错了什么?
【问题讨论】:
标签: javascript reactjs