[英]Edit User Details using React
I am stuck on editing user details and updating it.我坚持编辑用户详细信息并更新它。
What I'm trying to accomplish is when I click on "update" button, I can edit their name and email.我想要完成的是当我点击“更新”按钮时,我可以编辑他们的名字和电子邮件。 And I can also delete the entry by clicking the "delete" button.我还可以通过单击“删除”按钮来删除该条目。
I have added the ability to add new User which I am able to code.我添加了添加新用户的功能,我可以编写代码。
This is my code: https://codesandbox.io/s/zen-browser-5ifrel?file=/src/User.js这是我的代码: https ://codesandbox.io/s/zen-browser-5ifrel?file=/src/User.js
How do I add a if-else statement in my render so that IF i click on "update" button on one of the entry (eg, id === selected.id), it will transform the "name" and "email" to textboxes to allow for edit.如何在渲染中添加 if-else 语句,以便如果我单击其中一个条目上的“更新”按钮(例如,id === selected.id),它将转换“名称”和“电子邮件”到文本框以允许编辑。 And 2 buttons for them to "confirm" their update or "cancel" their update.还有 2 个按钮供他们“确认”他们的更新或“取消”他们的更新。
render() {
return (
<div className="App">
{
this.state.users.map((u) => {
return (
<React.Fragment key={u._id}>
<div className="box">
<h3>{u.name}</h3>
<h4>{u.email}</h4>
<button onClick={() => {
this.beginEdit(u);
}}
>Update
</button>
<button onClick={() => {
this.deleteUser(u);
}}
>Delete
</button>
</div>
</React.Fragment>
);
})}
{this.renderAddUser()}
</div>
);
}
Use conditional rendering .使用条件渲染。
render() {
return (
<div className="App">
{
this.state.users.map((u) => {
return (
<React.Fragment key={u._id}>
<div className="box">
{u.isEditing ? (
<React.Fragment>
<input type="text" placeholder="name" />
<input type="text" placeholder="email" />
</React.Fragment>
) : (
<React.Fragment>
<h3>{u.name}</h3>
<h4>{u.email}</h4>
</React.Fragment>
)}
<button onClick={() => {
this.beginEdit(u);
}}
>Update
</button>
<button onClick={() => {
this.deleteUser(u);
}}
>Delete
</button>
</div>
</React.Fragment>
);
})}
{this.renderAddUser()}
</div>
);
}
You can probably figure out the rest.您可能会弄清楚其余部分。
you can use this that render output depends on the condition of (id === selectedUser.id)您可以使用它来渲染输出取决于 (id === selectedUser.id) 的条件
state = {
selected = null;
}
render() {
return (
<div className="App">
{this.state.users.map((user) => {
return (
<div className="box" >
{selected?.id === user?._id ? (
<>
<input type="text" placeholder="name" defaultValue={user.name} />
<input type="text" placeholder="email" defaultValue={user.email} />
<button onClick={() => { this.handleCancel(user);}}>
Cancel
</button>
<button onClick={() => { this.handleConfirm(user);}}>
Confirm
</button>
</>
) : (
<>
<h3>{user.name}</h3>
<h4>{user.email}</h4>
<button onClick={() => { this.beginEdit(user);}}>
Update
</button>
<button onClick={() => { this.deleteUser(user);}}>
Delete
</button>
</>
)}
</div>
);
})}
{this.renderAddUser()}
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.