react-hooks - 我正在尝试通过单击表格行来绑定联系人字段中的联系人 ID
问题描述
我试图通过单击表格行来绑定联系人字段中的联系人 ID。已过滤并绑定来自 API 的数据在表行中。如果我单击要在联系人字段中绑定联系人 ID 的行。这是代码。请帮助我做到这一点。
这是过滤和映射功能。
const displayList = contact
.filter((contact) => {
const firstName = contact.firstName;
const lastName = contact.lastName;
const fullName = `${firstName} ${lastName}`;
if (searchTerm === "") {
return contact;
} else if (fullName.toLowerCase().includes(searchTerm.toLowerCase())) {
return contact;
}
})
.map((contact, index) => {
const firstName = contact.firstName;
const lastName = contact.lastName;
const fullName = `${firstName} ${lastName}`;
return (
<tr key={index}>
<td style={{ width: "1%" }}>{contact.id}.</td>
<td style={{ width: "5%" }}>{contact.contactID}</td>
<td style={{ width: "5%" }}>{fullName}</td>
</tr>
);
});
这是表格:
<div className="form-group col-md-6 ml-1">
<label htmlFor="Category">Contact Id</label>
<Field
type="text"
className={`form-control form-control-sm ${
getError(UserError, Usertouched, "contactId")
? "is-invalid"
: ""
}`}
name="contactId"
value={Uservalue.contactId || ""}
></Field>
<button
className="btn btn-primary openModalBtn"
type="submit"
onClick={() => {
setModalOpen(true);
}}
>
Search
</button>
{modalOpen ? (
<div className="card shadow">
<div className="card-body">
<div className="row">
<div className="col-lg-8 mt-3">
<form>
<input
type="text"
className="form-control"
placeholder="Search here"
value={searchTerm}
onChange={onChangeSearchTitle}
/>
{/* <button type="submit"><i class="fa fa-search"></i></button> */}
</form>
</div>
</div>
</div>
</div>
) : null}
{searchTerm ? (
<div className="table-responsive mt-5">
<table className="table table-striped">
<thead>
<tr>
<th style={{ width: "1%" }}>id</th>
<th style={{ width: "5%" }}>Contactid</th>
<th style={{ width: "5%" }}>Name</th>
</tr>
</thead>
<tbody>{displayList}</tbody>
</table>
</div>
) : null}
<ErrorMessage
name="contactId"
component="div"
className="invalid-feedback"
/>
</div>
解决方案
使用本地组件状态将允许您实现这一点,例如:
function ContactPage() {
const [contactId, setContactId] = useState()
...
<tr key={index} onclick={() => setContactId(id)}>
...
}
推荐阅读
- classification - 当预测数据中存在决策树模型中不可用的属性值时如何处理
- react-native - 如何在 react-native 中连接到 ftp 服务器?
- python - pandas 向量化优化-python
- javascript - 如何使下拉菜单扩展到右侧而不是向下?
- discord.js - DiscordJS 反转图像命令不显示任何内容
- c++ - 将数据复制到另一个任务
- python - 使用虚拟环境时,jupyter notebook 中使用了哪些模块?
- java - 如何在 Java 中生成内部分离的 XML 签名
- python - 约束中的“或”:docplex
- c# - UnityEvent 没有被调用