我正在尝试创建一个表单并将其值存储在状态中-到目前为止,如此合理。
我认为我已经把它设置好了,但是当我返回状态的内容时,每个字段都返回未定义状态。我毫不怀疑在设置过程中我忽略了一些简单的事情,但是我一生都无法看到它是什么...
有人可以让我摆脱痛苦吗?
handleAddProperty = (event) => {
event.preventDefault();
console.log(this.state.fields);
console.log(this.state.fields.type);
};
handleFieldChange = (event) => {
this.setState({
fields: {
title: event.target.value.title,
type: event.target.value.type,
bedrooms: event.target.value.bedrooms,
bathrooms: event.target.value.bathrooms,
price: event.target.value.price,
city: event.target.value.city,
email: event.target.value.email,
},
});
};
render() {
return (
<div className="addproperty">
<form onSubmit={this.handleAddProperty}>
<button type="submit">Add</button>
<input name="title" value={this.state.fields.title} onChange={this.handleFieldChange} />
<select name="type" value={this.state.fields.type} onChange={this.handleFieldChange}>
<option value={this.state.fields.type}>Flat</option>
<option value={this.state.fields.type}>Detached</option>
<option value={this.state.fields.type}>Semi-Detached</option>
<option value={this.state.fields.type}>Terraced</option>
<option value={this.state.fields.type}>End of Terrace</option>
<option value={this.state.fields.type}>Cottage</option>
<option value={this.state.fields.type}>Bungalow</option>
</select>
<input name="bedrooms" value={this.state.fields.bedrooms} onChange={this.handleFieldChange} />
<input name="bathrooms" value={this.state.fields.bathrooms} onChange={this.handleFieldChange} />
<input name="price" value={this.state.fields.price} onChange={this.handleFieldChange} />
<select name="city" value={this.state.fields.city} onChange={this.handleFieldChange}>
<option value={this.state.fields.city}>Manchester</option>
<option value={this.state.fields.city}>Leeds</option>
<option value={this.state.fields.city}>Sheffield</option>
<option value={this.state.fields.city}>Liverpool</option>
</select>
<input name="email" value={this.state.fields.email} onChange={this.handleFieldChange} />
</form>
</div>
);
}
}
答案 0 :(得分:1)
您应该访问event.target.value
而不是event.target.value[key]
,因为handleFieldChange
函数会为每个输入字段(当它们更改状态时)以及每个触发event.target
进行触发指的是其他输入字段(基本上是已更改的输入)。
要更新状态,可以使用event.target.name
作为组件状态内表单对象成员的键。该代码可能如下所示:
constructor(props) {
super(props);
this.state = { form: { name: 'Jane' } };
}
handleFieldChange(event) {
// This will update specific key in your form object inside the local state
this.setState({
form: Object.assign({}, this.state.form, {
[event.target.name]: event.target.value,
}),
});
}
<input
name="test"
type="text"
onChange={e => this.handleFieldChange(e)}
/>