【发布时间】:2020-06-04 19:46:44
【问题描述】:
在 app.js 中显示 Modal 时,点击各个人的“查看更多”按钮,只能看到最后一个人的模态数据。
链接:-https://codesandbox.io/s/lucid-tree-kjoim?file=/src/App.js
【问题讨论】:
标签: javascript html reactjs
在 app.js 中显示 Modal 时,点击各个人的“查看更多”按钮,只能看到最后一个人的模态数据。
链接:-https://codesandbox.io/s/lucid-tree-kjoim?file=/src/App.js
【问题讨论】:
标签: javascript html reactjs
在 DOM 中有一个模态实例(通常通过反应门户进行管理),因此当您映射每个人并创建一个模态时,最后一组胜出。您可以重构代码以仅呈现单个 Modal 并设置您希望在其中显示的人。
/**
* Manage modal instance
*/
const [selectedPerson, setSelectedPerson] = useState({});
const openModal = person => {
setSelectedPerson(person);
toggleModal(true);
};
const closeModal = () => {
setSelectedPerson({});
toggleModal(false);
};
在按钮的 onClick 处理程序的映射中,您要调用 openModal 来设置人员和打开状态。
.map(person => {
return (
<Col sm="4">
<EmployeeCard key={person.id} person={person} />
<button onClick={() => openModal(person)}>VIEW MORE</button>
</Col>
);
});
将Modal 移动到渲染函数的末尾,并使用selectedPerson 对象和closeModal 回调。
<Modal isOpen={isModalOpen} toggle={toggleModal}>
<h1>
NAME: {selectedPerson.firstName} {selectedPerson.lastName}
</h1>
<h3>AGE: {selectedPerson.age}</h3>
<p>{selectedPerson.bio}</p>
<button onClick={closeModal}>CLOSE</button>
</Modal>
【讨论】:
openModal 作为道具传递给EmployeeCard,将onClick={() => openModal(person)} 附加到CardImg。沙盒已更新。