如何在 Material-UI 的 Accordion 组件中将文本居中对齐?

How to align text to center in Accordion Component of Material-UI?

这是我的手风琴组件:

我希望上面的组件看起来像这样:

我想让这些标题(Accordion 1、Accordion 2)居中对齐。但是我做不到。

请帮忙,下面是来自Material-UI网站的代码:

import Accordion from '@material-ui/core/Accordion';
import AccordionSummary from '@material-ui/core/AccordionSummary';
import AccordionDetails from '@material-ui/core/AccordionDetails';
import Typography from '@material-ui/core/Typography';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';

export default function SimpleAccordion() {
  return (
    <div>
      <Accordion>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon />}
          aria-controls="panel1a-content"
          id="panel1a-header"
        >
          <Typography>Accordion 1</Typography>
        </AccordionSummary>
        <AccordionDetails>
          <Typography>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse
            malesuada lacus ex, sit amet blandit leo lobortis eget.
          </Typography>
        </AccordionDetails>
      </Accordion>
      <Accordion>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon />}
          aria-controls="panel2a-content"
          id="panel2a-header"
        >
          <Typography>Accordion 2</Typography>
        </AccordionSummary>
        <AccordionDetails>
          <Typography>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse
            malesuada lacus ex, sit amet blandit leo lobortis eget.
          </Typography>
        </AccordionDetails>
      </Accordion>
      <Accordion disabled>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon />}
          aria-controls="panel3a-content"
          id="panel3a-header"
        >
          <Typography>Disabled Accordion</Typography>
        </AccordionSummary>
      </Accordion>
    </div>
  );
}

Material-Ui 组件 Link: https://next.material-ui.com/components/accordion/#basic-accordion

为了使这个标题出现在中间,有一个class“MuiAccordionSummary-content”。

By-default,就是display:flex

现在,您需要将唯一的 属性 添加到这个名为 MuiAccordionSummary-content 的 class justify-content:居中;

要覆盖 css,请访问 link: Style Customisation in Material UI

有时,我们必须覆盖组件的默认行为,或者说根据我们的要求覆盖样式。

如果您不想直接覆盖它,请使用内联样式或特定的 class名称,就像我们对普通 css.

所做的那样

代码

首先我们使用 useStyles() API:

创建我们的样式
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
  content: {
    justifyContent: "center"
  }
});

接下来,在每个 AccordionSummary 组件中,我们使用 classes 属性应用样式,如下所示:

<AccordionSummary
  classes={{ content: classes.content }}  // <-- Add this line
  /* ... */
>

说明

参考documentation on customizing components中的例子,我们打开Chrome DevTools检查手风琴:

请注意,内容容器的 class 名称是 MuiAccordionSummary-content。这意味着我们可以使用以下格式将样式应用于 AccordionSummary 组件:

<AccordionSummary classes={{ content: XXXX }} />

因此,我们使用 makeStyles API 定义一个名为 content 的样式对象,然后我们使用此对象为每个 AccordionSummary 组件设置样式。