Gatsby项目中如何给非MUI原生标签应用MUI Typography等同样式
实现方案
核心原理:MUI Typography组件的所有基础样式都来源于theme.typography对象下对应variant的配置,直接将这些配置应用到原生HTML标签即可实现样式对齐。
方案1:全局样式注入(适合全站用户内容统一适配)
使用MUI官方提供的GlobalStyles组件注入全局样式,直接给所有对应原生标签应用Typography样式,无需修改用户生成的内容标签。
代码示例:
import { Typography, GlobalStyles } from "@mui/material" export default function() { return ( <> <GlobalStyles styles={theme => ({ // 匹配body1 + paragraph属性的p标签样式 p: { ...theme.typography.body1, marginBottom: theme.spacing(2), }, // 其他需要对齐的标签按需添加 h1: theme.typography.h1, h2: theme.typography.h2, ul: theme.typography.body1, })} /> <Typography variant="body1" paragraph>My styled Typography</Typography> {/* 无需做任何修改的用户生成内容 */} <p>my custom user content - how can i style this like above?</p> </> ) }
方案2:容器隔离样式(适合仅特定区域用户内容适配)
如果不想污染全局原生标签的样式,可以创建一个专属容器组件,只对容器内的原生标签应用样式,隔离性更强。
代码示例:
import { Typography, styled } from "@mui/material" // 创建用户内容专属容器 const UserContentContainer = styled('div')(({ theme }) => ({ p: { ...theme.typography.body1, marginBottom: theme.spacing(2), }, h1: theme.typography.h1, h2: theme.typography.h2, })) export default function() { return ( <> <Typography variant="body1" paragraph>My styled Typography</Typography> {/* 用户生成的所有内容都放在该容器内 */} <UserContentContainer> <p>my custom user content - how can i style this like above?</p> </UserContentContainer> </> ) }
两种方案都完全兼容styled-components样式引擎,且无需修改用户生成的任何HTML标签结构,就能实现和官方Typography组件完全一致的样式效果。
内容的提问来源于stack exchange,提问作者dotist
相关产品推荐
相关产品推荐

