简体   繁体   English

onClick 事件打开所有 Material-UI 对话框

[英]onClick event opens all Material-UI dialogs

I am trying to do a simple employee "rolodex" and want it to display employee information when they click on the card via Material-UIs dialog modals.我正在尝试做一个简单的员工“rolodex”,并希望它在他们通过 Material-UIs 对话框模式单击卡片时显示员工信息。 When I click on any one ALL dialog boxes open and not just the one I want.当我单击任何一个时,所有对话框都会打开,而不仅仅是我想要的。 Here's what I got:这是我得到的:

const [isModalOpen, setIsModalOpen] = useState(false);

const openModal = () => {
  setIsModalOpen(true);
}

const closeModal = () => {
  setIsModalOpen(false);
}

<Grid continer>
  {employees && employees.map(e => (
    <Grid item md={4}>
      <Card onClick={openModal}>
        <CardContent>
          <p>{e.name}</p>
        </CardContent>
      </Card>
    </Grid>

    <Dialog
      open={isModalOpen}
      onClose={closeModal}
    >
      <DialogTitle>{e.name}</DialogTitle>
      <DialogContent>
        <DialogContentText>
          <p>Department: {e.department}</p>
          <p>Phone: {e.phone}</p>
          <p>Email: {e.email}</p>
        </DialogContentText>
      </DialogContent>
    </Dialog>
  ))}
</Grid>

Thanks in advance for any help/suggestions!提前感谢您的任何帮助/建议!

You will need a different piece of state to track which employee is selected:您将需要另一块 state 来跟踪选择了哪个员工:

const [selectedEmployee, setSelectedEmployee] = useState(null);

const openModal = (employeeId) => {
  setSelectedEmployee(employeeId);
}

const closeModal = () => {
  setSelectedEmployee(null);
}

<Grid continer>
  {employees && employees.map(e => (
    <Grid item md={4}>
      <Card onClick={() => openModal(e.id)}>
        <CardContent>
          <p>{e.name}</p>
        </CardContent>
      </Card>
    </Grid>

    <Dialog
      open={selectedEmployee === e.id}
      onClose={closeModal}
    >
      <DialogTitle>{e.name}</DialogTitle>
      <DialogContent>
        <DialogContentText>
          <p>Department: {e.department}</p>
          <p>Phone: {e.phone}</p>
          <p>Email: {e.email}</p>
        </DialogContentText>
      </DialogContent>
    </Dialog>
  ))}
</Grid>

I just assumed you had id on employee record, but another unique field could be used.我只是假设您在员工记录上有id ,但可以使用另一个唯一字段。 Having a single boolean and using it would set all of the modals open as you experienced.拥有一个 boolean 并使用它会将所有模态设置为您所经历的打开状态。 By storing the employee Id (or other unique field) that is clicked, you can use that to decide which of the modals should be opened.通过存储单击的员工 ID(或其他唯一字段),您可以使用它来决定应打开哪些模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM