展开手风琴摘要时如何更改图标?

How to change icon when accordion summary is expanded?

我想根据手风琴是否展开来更改图标。

我在 material ui 页面上看到 CSS 有 .Mui-expanded 可以查看 expanded={true} 还是 false,但是我如何使用这在展开时设置不同的图标是 true 还是 false。

所以我想在 expand 为 true 时设置 IconA,在 expand 为 false 时设置 IconB。

expandIcon={<IconA/>}

您可以使用可用于 AccordionSummary 组件的 expandIcon 道具。像这样设置条件:expandIcon={expanded === 'panel1'?<ExpandMoreIcon />:<Minimize/>}

<Accordion expanded={expanded === 'panel1'} onChange={handleChange('panel1')}>
    <AccordionSummary
      expandIcon={expanded === 'panel1'?<ExpandMoreIcon />:<Minimize/>}
      aria-controls="panel1bh-content"
      id="panel1bh-header"
    >
      <Typography className={classes.heading}>General settings</Typography>
      <Typography className={classes.secondaryHeading}>I am an accordion</Typography>
    </AccordionSummary>
    <AccordionDetails>
      <Typography>
        Nulla facilisi. Phasellus sollicitudin nulla et quam mattis feugiat. Aliquam eget
        maximus est, id dignissim quam.
      </Typography>
    </AccordionDetails>
  </Accordion>

此示例代码取自文档:https://material-ui.com/components/accordion/#controlled-accordion

你可以使用条件渲染

     <Accordion
      key={index + 1}
      className={style.accordianMargin}
      expanded={expanded === index + 1}
      onChange={handleChange(index + 1)}
    >
      <AccordionSummary
        expandIcon={
          expanded && opened === index + 1 ? <RemoveIcon /> : 
                                                <AddIcon />
        }
      >

上面提到的解决方案 is absolutely right but has the disadvantage that you must use a useState hook to show a different icon when the accordion is collapsed/expanded. This makes it however difficult (impossible?) to specify a custom expandIcon globally in the Theme. Therefore Mui should in my opinion pass the expand state to the expandIcon prop. There is a feature request for this https://github.com/mui/material-ui/issues/18326但是还没有实现。作为上述解决方案的变通方法和替代方案,它的好处是可以在全球主题中使用,可以通过这种方式提供自定义图标:

  const CustomExpandIcon = () => {
    return (
      <Box
        sx={{
          '.Mui-expanded & > .collapsIconWrapper': {
            display: 'none',
          },
          '.expandIconWrapper': {
            display: 'none',
          },
          '.Mui-expanded & > .expandIconWrapper': {
            display: 'block',
          },
        }}
      >
        <div className="expandIconWrapper">
          <MinusIcon />
        </div>
        <div className="collapsIconWrapper">
          <PlusIcon />
        </div>
      </Box>
    )
  }

参见:https://codesandbox.io/s/basicaccordion-material-demo-forked-2916o