如何使用样式组件覆盖ExpansionPanelSummary深层元素?

时间:2019-03-29 23:58:20

标签: javascript css material-ui styled-components

使用the docs/examples通过样式化组件覆盖Material UI样式,我设法在ExpansionPanelExpansionPanelDetails中设置了根元素和“更深的元素”。

但是,当我使用相同的技术从传递给ExpansionPanelSummary的函数返回重写的styled()时,ExpansionPanelSummary在DOM中移动,整个ExpansionPanel不在更长的时间才能正确渲染。

应用于ExpansionPanel的相关技术(按预期在容器ExpansionPanel上起作用)

import MUIExpansionPanel from '@material-ui/core/ExpansionPanel';

export const ExpansionPanel = styled(props => (
  <MUIExpansionPanel
    classes={{expanded: 'expanded'}}
    {...props}
  />
))`
  && {
    ...root style overrides
  }
  &&.expanded {
    ...expanded style overrides
  }
`;

ExpansionPanel和朋友的典型DOM(缩写为类名):

<div class="MuiExpansionPanel...">
  <div class="MuiExpansionPanelSummary..." />
  <div class="MuiCollapse-container...>
    <div class="MuiCollapse-wrapper...>
      <div class="MuiCollapse-wrapperInner...>
        <div class="MuiExpansionPanelDetails..." />
      </div>
    </div>
  </div>
</div>

将上述技术应用于ExpansionPanelSummary时的DOM:

<div class="MuiExpansionPanel...">
  <div class="MuiCollapse-container...>
    <div class="MuiCollapse-wrapper...>
      <div class="MuiCollapse-wrapperInner...>
        <div class="MuiExpansionPanelSummary..." />
        <div class="MuiExpansionPanelDetails..." />
      </div>
    </div>
  </div>
</div>

为完整起见,这是我对ExpansionPanelSummary做的事情的最小复制,它会触发DOM切换:

export const ExpansionPanelSummary = styled(props => (
  <MUIExpansionPanelSummary
    {...props}
  />
))``;

我的JSX是标准的ExpansionPanel设置:

<ExpansionPanel>
  <ExpansionPanelSummary>
    Summary Label
  </ExpansionPanelSummary>
  <ExpansionPanelDetails>
    <div>Some Content</div>
  </ExpansionPanelDetails>
</ExpansionPanel>

1 个答案:

答案 0 :(得分:1)

此困难与使用样式组件无关,而与将ExpansionPanelSummary包装在另一个组件中有关。

您可以使用以下ExpansionPanelSummary换行来类似地重现此内容:

const MyCustomSummary = props => {
  return (
    <ExpansionPanelSummary {...props} expandIcon={<ExpandMoreIcon />}>
      <Typography>{props.text}</Typography>
    </ExpansionPanelSummary>
  );
};

有几个类似的组件组,其中Material-UI父组件寻找特定类型的子组件,并特别对待该子组件。例如,您可以在ExpansionPanel

中找到以下块
      if (isMuiElement(child, ['ExpansionPanelSummary'])) {
        summary = React.cloneElement(child, {
          disabled,
          expanded,
          onChange: this.handleChange,
        });
        return null;
      }

幸运的是,Material-UI可以通过muiName属性直接告诉您自定义组件与特定的Material-UI组件相同:

MyCustomSummary.muiName = "ExpansionPanelSummary";

或者在您的情况下看起来像这样:

export const ExpansionPanelSummary = styled(props => (
  <MUIExpansionPanelSummary
    {...props}
  />
))``;

ExpansionPanelSummary.muiName = "ExpansionPanelSummary";

Edit Custom ExpansionPanelSummary