MUI V5样式(排版)变体不工作



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

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

如果style Typography写成如下,的变体实际上不生效。我能问一下为什么不行吗?代码应该是什么样的?谢谢。

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

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

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

你也可以把一个prop传递给样式化的组件。

<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

首先检查你的导入是否样式来自@mui/materials/styles,如果你通过stylesed -components导入它可能会遇到一些问题。

看这里: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