您只需使用
type
将每个phone对象的
select
要素
这是最新消息
stackblitz
.
const PhoneTypes = ['Mobile', 'Home', 'Office'];
class Questionnaire extends Component {
state = {
phones: [{ type: 'Mobile', number: '' }],
};
addContact() {
this.setState((prevState) => ({
phones: [...prevState.phones, { type: 'Mobile', number: '' }],
}));
}
handleChange({ target: { name, value } }, phoneIndex) {
this.setState((prevState) => ({
phones: prevState.phones.map((phone, index) =>
phoneIndex === index ? { ...phone, [name]: value } : phone
),
}));
}
handleRemove(phoneIndex) {
this.setState((prevState) => ({
phones: prevState.phones.filter((_, index) => phoneIndex !== index),
}));
}
handleSubmit(e) {
console.log(this.state, '$$$');
}
render() {
return (
<div>
<h1>The Form</h1>
<label>Contact</label>
{this.state.phones.map((phone, index) => {
return (
<div key={index}>
<input
onChange={(e) => this.handleChange(e, index)}
value={phone.number}
name="number"
/>
<select
name="type"
value={phone.type}
onChange={(e) => this.handleChange(e, index)}
>
{PhoneTypes.map((phoneType, index) => {
return (
<option key={index} value={phoneType}>
{phoneType}
</option>
);
})}
</select>
<button onClick={(e) => this.handleRemove(index)}>Remove </button>
</div>
);
})}
<hr />
<button onClick={(e) => this.addContact(e)}>Add contact</button>
<hr />
<button onClick={(e) => this.handleSubmit(e)}>Submit</button>
</div>
);
}
}
我还修复了一些其他问题,如改变状态、不正确的参数以删除函数等。