【发布时间】:2021-03-29 00:08:24
【问题描述】:
我正在使用 React.JS 开发一个应用程序,我必须显示进一步详细说明所选表格元素的信息。
我分享一张图片作为解释,以便人们理解它或我需要做什么。
我该怎么做?我知道您必须将变量传递给弹出窗口,以便根据所选元素获取和显示它们。
【问题讨论】:
标签: javascript arrays json reactjs api
我正在使用 React.JS 开发一个应用程序,我必须显示进一步详细说明所选表格元素的信息。
我分享一张图片作为解释,以便人们理解它或我需要做什么。
我该怎么做?我知道您必须将变量传递给弹出窗口,以便根据所选元素获取和显示它们。
【问题讨论】:
标签: javascript arrays json reactjs api
对于这个用例,在组件中创建一个本地状态,并在单击所选记录时更新详细信息,并将状态传递给模态。
在这里,我创建了一个selectedData 状态,用于填充选定的记录并在表中more details 的 onClick 时更新此状态,并将它们作为道具传递给模态,以便它显示在 UI 中。
完整代码:-
import React, { useState } from "react";
import "./styles.css";
import "bootstrap/dist/css/bootstrap.min.css";
const data = [
{
id: 1001,
firstname: "Mark",
lastname: "Otto",
age: 34,
location: "London",
address: "10 Downing Street"
},
{
id: 1002,
firstname: "Jacob",
lastname: "Jacob",
age: 34,
location: "India",
address: "#110 broad Street"
}
];
export default function App() {
const [show, setShow] = useState(false);
const [selectedData, setSelectedData] = useState({});
const hanldeClick = (selectedRec) => {
setSelectedData(selectedRec);
setShow(true);
};
const hideModal = () => {
setShow(false);
};
return (
<div className="App">
<table class="table">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Location</th>
<th scope="col">Show More</th>
</tr>
</thead>
<tbody>
{data.map((v) => (
<tr>
<td>{v.id}</td>
<td>{v.firstname}</td>
<td>{v.lastname}</td>
<td>@{v.location}</td>
<td>
<a href="#" onClick={() => hanldeClick(v)}>
More details
</a>
</td>
</tr>
))}
</tbody>
</table>
{show && <Modal details={selectedData} handleClose={hideModal} />}
</div>
);
}
const Modal = ({ handleClose, details }) => {
return (
<div className="modal display-block">
<section className="modal-main">
<div className="App">
<table class="table">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Age</th>
<th scope="col">Location</th>
<th scope="col">Address</th>
</tr>
</thead>
<tbody>
<tr>
<td>{details?.id}</td>
<td>{details?.firstname}</td>
<td>{details?.lastname}</td>
<td>{details?.age}</td>
<td>{details?.location}</td>
<td>{details?.address}</td>
</tr>
</tbody>
</table>
</div>
<button onClick={handleClose}>close</button>
</section>
</div>
);
};
工作演示 - https://codesandbox.io/s/awesome-lamarr-hy8hu?file=/src/App.js:0-2625
希望您正在寻找相同的用例。如果您遇到任何问题,请告诉我。
【讨论】: