フォームを作成し、その値を状態で保存しようとしています–これまでのところ、非常に合理的です。
私はそれをすべて正しく設定したと思いますが、状態の内容を返すと、すべてのフィールドが未定義で返されます。設定する際に見落としていた簡単なものがあることは間違いありませんが、それが何であるかを一生見ることはできません...
誰かが私の悲惨さから私を追い出すことができますか?
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>
);
}
}
各入力フィールド(状態が変更されたとき)およびその各トリガーの関数トリガーは異なる入力フィールド(基本的には変更された入力)を参照しているため、に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)}
/>
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加