我有一个带有Edit
按钮的联系人列表。单击后,我要使<div>
带有输入出现。当前,单击该按钮时,将为我的联系人列表中的所有元素显示此<div>
。
这是代码。我没有在这里放置从API等中获取联系人的代码。
```
class App extends Component {
state = {
contacts: [],
firstName: '',
lastName: '',
phoneNumber: '',
email: '',
editVisible: true
};
showEditDiv = (id) => {
this.setState({
editVisible: !this.state.editVisible
})
};
render() {
const visibility = this.state.editVisible ? 'unvisible' : 'visible';
return (
<ul>
{this.state.contacts.map(contact => {
return (
<div>
<li key={contact.id}>
<p>{contact.firstName} {contact.lastName}</p>
<p>{contact.phoneNumber}</p>
<p>{contact.email}</p>
<button onClick={() => this.removeContact(contact.id)}>Remove</button>
<button onClick={() => this.showEditDiv(contact.id)}>Edit</button>
<div key={contact.id} className={`edit-form ${visibility}`}>
<p>This is edit form</p>
</div>
</li>
</div>
)
})}
</ul>
</div>
);
}
}
export default App;
.edit-form { height: 100px; background: #a7a7a7; } .unvisible { display: none; } .visible { display: block; }
答案 0 :(得分:2)
根据您的情况,您需要在状态中保留一个单独的属性,并设置各个项目的可见性。这是一个工作示例。如果您是我,我会将联系人项目提取到其自己的组件中,并摆脱那些在您的onClick
处理程序中调用的函数。
class App extends React.Component {
state = {
contacts: [
{ id: 1, firstName: "foo", lastName: "foo", email: "foo@foo.com"},
{ id: 2, firstName: "bar", lastName: "bar", email: "bar@bar.com" },
],
firstName: '',
lastName: '',
phoneNumber: '',
email: '',
editVisibles: {},
};
showEditDiv = (id) => {
this.setState( prevState => ({
editVisibles: { ...prevState.editVisibles, [id]: !prevState.editVisibles[id] }
}))
};
render() {
return (
<ul>
{this.state.contacts.map(contact => {
return (
<div>
<li key={contact.id}>
<p>{contact.firstName} {contact.lastName}</p>
<p>{contact.email}</p>
<button onClick={() => this.removeContact(contact.id)}>Remove</button>
<button onClick={() => this.showEditDiv(contact.id)}>Edit</button>
<div key={contact.id} className={`edit-form ${!this.state.editVisibles[contact.id] ? "unvisible" : "visible"}`}>
<p>This is edit form</p>
</div>
</li>
</div>
)
})}
</ul>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
.edit-form {
height: 100px;
background: #a7a7a7;
}
.unvisible {
display: none;
}
.visible {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
答案 1 :(得分:1)
您可以使用'contact.id`代替editVisible
,这意味着:
showEditDiv = (id) => {
this.setState(prevState => ({ editingContactId: prevState.editingContactId === id? null:id}))
};
并且div将是:
<div key={contact.id} className={contact.id === this.state.editingContactId?'edit-form visible' :'edit-form unvisible'}>
...
</div>