我有一个React表单,当前在items
数组中存储一个表单字段值。但是,当添加多个字段时,我也无法将其他字段的内容存储在数组中。它目前存储First Name
输入的值,但无法确定Last Name
和Phone
字段。然后,数据将呈现给items
数组到3列表,但无法将其他字段显示在各自的列中。
Contacts.js
import ContactList from "./ContactList";
class Contacts extends Component {
constructor(props) {
super(props);
this.state = {
items: []
};
this.addItem = this.addItem.bind(this);
this.deleteItem = this.deleteItem.bind(this);
}
addItem(e) {
if(this._inputElement.value !== "") {
var newItem = {
firstname: this._inputElement.value,
lastname: this._inputElement2.value,
phonename: this._inputElement3.value,
key: Date.now()
};
this.setState((prevState) => {
return {
items: prevState.items.concat(newItem)
};
});
this._inputElement.value = "";
this._inputElement2.value = "";
this._inputElement3.value = "";
}
console.log(this.state.items);
e.preventDefault();
}
deleteItem(key) {
var filteredItems = this.state.items.filter(function (item) {
return (item.key !== key);
});
this.setState({
items: filteredItems
});
}
render () {
return (
<Panel>
<Tabs onChange={this.onChange} defaultSelectedIndex={0} justified={true}>
<Tab value="pane-1" label="Add Contact" onActive={this.onActive}>
<Form onSubmit={this.addItem}>
<input ref={(a) => this._inputElement = a}
placeholder="First Name" />
<input ref={(a) => this._inputElement2 = a}
placeholder="Last Name" />
<input ref={(a) => this._inputElement3 = a}
placeholder="Phone" />
<Button variant="raised">Add</Button>
</Form>
</Tab>
<Tab value="pane-2" label="List Contacts">
<ContactList entries={this.state.items}
delete={this.deleteItem}/>
</Tab>
</Tabs>
</Panel>
);
}
}
export default Contacts
联系人列表
class ContactList extends Component {
constructor(props) {
super(props);
this.createContact = this.createContact.bind(this);
}
delete(key) {
this.props.delete(key);
}
createContact(item) {
return
<tr key={item.key}>
<td onClick={() => this.delete(item.key)}>{item.firstname}</td>,
<td>{item.lastname}</td>
<td>{item.phone}</td>
</tr>
}
render() {
var contactEntries = this.props.entries;
var listItems = contactEntries.map(this.createContact);
return (
<table className="mui-table">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr>
{listItems}
</tr>
</tbody>
</table>
);
}
};
export default ContactList;
答案 0 :(得分:0)
这是答案。你刚刚点击this._inputElement ref只保存它的值,而在你的表单中你还有两个输入。我的建议检查最新的更新反应更新。他们不建议您使用&#34; REF&#34;一点都不。
addItem(e) {
if (this._inputElement.value !== "") {
var newItem = {
firstname: this._inputElement.value,
lastname: this._inputElement2.value,
phonename: this._inputElement3.value,
key: Date.now()
};
this.setState(prevState => {
return {
items: prevState.items.concat(newItem)
};
});
this._inputElement.value = "";
this._inputElement2.value = "";
this._inputElement3.value = "";
}