如何将样式化组件主题作为道具传递给 Material UI 组件?

问题描述

我花了 9 个小时寻找解决方案,我在任何地方都找不到任何似乎有效的方法

我正在用打字稿编写一个 React 组件。

我对 Material UI Accordian 有一个简单的使用:

const Accordion = withStyles({

root:{
    backgroundColor: 'rgb(193,195,191)',},rounded:{
    '&:last-child':{
    borderBottomLefTradius:'0px',borderBottomrighTradius:'0px','&:first-child':{
        borderTopLefTradius:'0px',borderTopRighTradius:'0px',}
}
})(MuiAccordian);

我想要做的就是传入我的样式化组件主题,以便我可以将其应用为 root=>backgroundColor 值。

我相信这里的某个向导会立即发现我的问题 - 我可以请人简单地展示如何将 DefaultTheme 对象类型的主题作为道具传递给 withStyles 方法吗?

非常感谢您的帮助。

编辑 - 代码解决方

感谢下面的@filippofilip,他的回答中的链接指向了让我解决这个问题的信息。

工作代码是:

const Accordion = withStyles(
    {
      root: (props:DefaultTheme) => ({
        backgroundColor: props.colors.backgroundColor,}),rounded: {
        '&:last-child': {
          borderBottomLefTradius: '0px',borderBottomrighTradius: '0px','&:first-child': {
          borderTopLefTradius: '0px',borderTopRighTradius: '0px',{ withTheme: true },)(MuiAccordian);

您会注意到从 Styled Components 解析 DefaultTheme 类型的 typed props 时略有不同。

为了从实现中调用它,我使用了 useContext 钩子来检索样式化组件主题并将其传递给道具:

export default function MyAccordianComponent() {
  
  const themeContext = useContext(ThemeContext);
  const classes = useStyles(themeContext);

  return (
    <div className={classes.root}>
      <Accordion {...themeContext} defaultExpanded >

---fill in the rest of the component below

我希望这有助于其他人寻找这个或类似的东西来处理样式化组件、Typescript 和 Material UI

解决方法

我认为您应该尝试查看此文档示例 https://material-ui.com/styles/basics/#adapting-based-on-props

通常主题在 props 参数内或作为来自该函数的第二个参数。

编辑:我在文档中发现您应该明确指定您希望在 props 对象中包含主题。

所以就这样使用它:

const Accordion = withStyles(
  {
    root: {
      backgroundColor: props => props.theme.backgroundColor,},rounded: {
      '&:last-child': {
        borderBottomLeftRadius: '0px',borderBottomRightRadius: '0px','&:first-child': {
        borderTopLeftRadius: '0px',borderTopRightRadius: '0px',{ withTheme: true },)(MuiAccordian);

要查看所有其他可用选项,请查看 HERE