【问题标题】:How can I expand the row only when that row was clicked?如何仅在单击该行时展开该行?
【发布时间】:2021-10-24 11:51:01
【问题描述】:

我有这个 materia-ui 表。每次我单击按钮展开第 1 行时,它也会展开第 2 行。我该如何解决这个问题,只有特定的行会扩展?

<Table stickyHeader aria-label="sticky table">
  <TableHead>
    <TableRow hover>
      <TableCell>Title</TableCell>
      <TableCell>Created Date</TableCell>
    </TableRow>
  </TableHead>
  <TableBody>
  {data &&
   data((index) => (
    <TableRow hover>
      <TableCell>
        <IconButton
          aria-label="expand row"
          size="small"
          onClick={() => setOpen(!open)}
          >
          {open ? (
            <KeyboardArrowUpIcon />
          ) : (
            <KeyboardArrowDownIcon />
          )}
          </IconButton>
        </TableCell>
        <TableCell component="th" scope="row">
          {index.title}
        </TableCell>
        <TableCell component="th" scope="row">
          {new Date(
            index.createdDate.seconds * 1000
          ).toDateString()}
        </TableCell>
        <TableCell colSpan={6}>
          <Collapse in={open} timeout="auto" unmountOnExit>
            {index.text}
          </Collapse>
        </TableCell>
      </TableRow>
     ))}
   </TableBody>
 </Table>

【问题讨论】:

  • 请为 TableRow 设置key
  • @hamedhossani 我试过这个{announcement &amp;&amp; announcement.map((index, i) =&gt; ( &lt;TableRow key={i}&gt; 但它没有用。即使我只点击一行,所有行都会展开

标签: javascript reactjs material-ui mui-datatable


【解决方案1】:

TableRow 包装在一个组件中

const Row = ({item}) => {
  const [open, setOpen] = useState(false);

  return <TableRow>...</TableRow>
}

<TableBody>
  {data.map((item, index) => (
    <Row key={index} item={item} />
  ))}
</TableBody>

【讨论】:

  • 我试着把它放在我的TableRow 上,但它不起作用
  • @RavenousRed 编辑了我的答案。
猜你喜欢
  • 2019-07-08
  • 2014-09-07
  • 1970-01-01
  • 2020-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-20
  • 1970-01-01
相关资源
最近更新 更多