【问题标题】:MUI V5 styled(Typography) variant not workMUI V5 样式(排版)变体不起作用
【发布时间】:2022-11-10 19:41:24
【问题描述】:

现在 Typography 变体是内联的,如下所示:

<Typography variant="h6">
  Any text
</Typography>

如果样式排版如下所示,则变体实际上并没有生效。请问为什么它不起作用?代码应该是什么样子?谢谢。

const StyledTypography = styled(Typography)(({ theme }) => ({
  variant: theme.typography.h6,
}));

<StyledTypography>
  Any text
</StyledTypography>

【问题讨论】:

    标签: material-ui variant typography


    【解决方案1】:

    如果您的目标只是使用 h6 变体,请将其作为道具传递。 variant 不是有效参数。

    <Typography variant="h6">
    
    </Typography>
    

    您还可以将道具传递给样式组件。

    <StyledTypography variant="h6">
      
    </StyledTypography>
    

    theme.typography.h6 是一个包含各种东西的对象,例如,lineHeightfontWeight 之类的东西。它不是你可以像这样作为样式属性传递的东西。

    您可以将此对象传播到一个样式化的组件中以实现您想要的结果,但同样不值得,只需使用 variant 作为道具。

    const StyledTypography = styled(Typography)(({ theme }) => ({
      ...theme.typography.h6 // Don't do this.
    }));
    
    export default function Example() {
      return (
        <StyledTypography>
          Just use normal Typography
        </StyledTypography>
      );
    }
    

    这是我所描述的一个简单的工作示例:https://codesandbox.io/s/variant-as-styled-parameter-zd975r?file=/src/App.js

    【讨论】:

      【解决方案2】:

      如果样式来自@mui/materials/styles,首先检查您的导入,如果您通过样式组件导入它,您可能会遇到一些问题。

      【讨论】:

        【解决方案3】:

        看看这里: https://styled-components.com/docs/advanced


        您可以通过以下方式访问数据 ${props => props.key}

        所以,

        改变

        const StyledTypography = styled(Typography)(({ theme }) => ({
          variant: theme.typography.h6,
        }));
        

        const StyledTypography = styled.div`
        variant: ${props => props.variant}
        `
        

        然后使用正确的键访问您的对象,

        props.variant.theme.typography.h6,例如。

        【讨论】:

        • 他们的问题与为什么它不能使用 MUI 样式的组件有关。您的解决方案没有解决这个问题。
        猜你喜欢
        • 2022-01-13
        • 2022-10-05
        • 2021-12-11
        • 2022-01-25
        • 2021-12-22
        • 1970-01-01
        • 2022-01-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多