【发布时间】:2019-07-10 06:28:05
【问题描述】:
我有一个表格,它只需要在提交时将值存储在状态中。 我这样做时遇到了问题,
-
我只在我的表单控件中获得最后一个输入的值,即:
formControls:限定:“a”
我收到此错误:警告:组件正在将文本类型的受控输入更改为不受控制。 输入元素不应从受控切换到不受控(反之亦然)。决定在组件的生命周期内使用受控输入元素还是不受控输入元素。
我理解了上述问题所以我在构造函数中声明了我的状态,所以我的输入元素甚至在 onChange 函数被触发之前就具有该值。 但这似乎也不能解决我的问题。
下面是我的代码:
import React, { Component } from 'react';
import './user.css';
class User extends Component {
constructor(props){
super(props);
this.state = {
formControls: {
name: "",
age: "",
occupation:"",
hometown: "",
qualification: ""
}
}
}
detailsHandler = (e) => {
const name = e.target.name;
const value = e.target.value;
console.log(name, value)
this.setState({
formControls: {
[name]: value
}
});
}
submitFormHandler = (e) => {
e.preventDefault();
console.log(this.state)
}
render() {
return (
<div>
<div className="main-container">
<div className="form-header">
<p className="">Fill details here</p>
</div>
<div className="form-container">
<form onSubmit={this.submitFormHandler}>
<div className="form-row">
<div className="form-label"><label>Name: </label></div>
<input type="text" placeholder="name" name="name" value={this.state.formControls.name} onChange={this.detailsHandler}/>
</div>
<div className="form-row">
<div className="form-label"><label>Age: </label></div>
<input type="text" placeholder="age" name="age" value={this.state.formControls.age} onChange={this.detailsHandler}/>
</div>
<div className="form-row">
<div className="form-label"><label>Occupation: </label></div>
<input type="text" placeholder="Occupation" name="occupation" value={this.state.formControls.occupation} onChange={this.detailsHandler}/>
</div>
<div className="form-row">
<div className="form-label"><label>Hometown: </label></div>
<input type="text" placeholder="Hometown" name= "hometown" value={this.state.formControls.hometown} onChange={this.detailsHandler}/>
</div>
<div className="form-row">
<div className="form-label"><label>Qualification: </label></div>
<input type="text" placeholder="Qualification" name="qualification" value={this.state.formControls.qualification} onChange={this.detailsHandler}/>
</div>
<div>
<input type="submit" value="SUBMIT" />
</div>
</form>
</div>
</div>
</div>
);
}
}
export default User;
谁能帮我弄清楚我做错了什么?
【问题讨论】:
标签: javascript reactjs react-redux-form