【问题标题】:Not able to display "Modal" for respective "viewmore" button无法为各自的“查看更多”按钮显示“模式”
【发布时间】:2020-06-04 19:46:44
【问题描述】:

在 app.js 中显示 Modal 时,点击各个人的“查看更多”按钮,只能看到最后一个人的模态数据。

链接:-https://codesandbox.io/s/lucid-tree-kjoim?file=/src/App.js

【问题讨论】:

    标签: javascript html reactjs


    【解决方案1】:

    在 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>
    

    【讨论】:

    • 我试图删除按钮并单击图像应该打开模式,但是图像是从 Employeecard.js 文件中显示的,所以可以将图像作为 onclick 选项,
    • @MILANSAI 是的,将openModal 作为道具传递给EmployeeCard,将onClick={() =&gt; openModal(person)} 附加到CardImg。沙盒已更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 2018-04-28
    相关资源
    最近更新 更多