首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将MUI样式应用于非MUI标记元素

将MUI样式应用于非MUI标记元素
EN

Stack Overflow用户
提问于 2021-11-12 10:29:41
回答 3查看 77关注 0票数 2

在我的Gatsby应用程序中,我使用的是MUI v5,并且还必须输出用户创建的标记。我希望用户标记获得与其类似的Typography元素相同的基本样式(见下文)。我如何才能做到这一点?

注意-用户标记已经包含<p> <h1>或其他标记,React不能直接修改这些标记。

此外,该应用程序与ThemeProvider一起包装,我使用styled-components作为MUI的样式引擎(如果这很重要的话…)。

代码语言:javascript
复制
import {Typography} from "@mui/material"
export default function() {
  return (
    <>
      <Typography variant="body1" paragraph>My styled Typography</Typography>
      // The next line can't receive any classses or modifiers, 
      // but must end up styled like the <Typography> element.
      <p>my custom user content - how can i style this like above?</p>
    </>
  )
}
EN

回答 3

Stack Overflow用户

发布于 2021-11-12 11:22:40

你需要导入你的主题。在那里,您可以访问应用于p元素的body1默认排版样式。

代码语言:javascript
复制
import {Typography} from '@mui/material'
import {useTheme} from //im not exactly sure where this comes from '@mui/material' or '@mui/styles'

export default function() {

  const theme = useTheme()

  return (
    <>
      <Typography variant="body1" paragraph>My styled Typography</Typography>
      <p style={theme.typography.body1}>my custom user content - how can i style this like above?</p>
    </>
  )
}
票数 1
EN

Stack Overflow用户

发布于 2021-11-12 13:29:24

代码语言:javascript
复制
import {useTheme ,Typography} from "@mui/material"
    
    export default function() {
    
      const theme = useTheme()
    
      return (
        <>
          <Typography variant="body1" paragraph>My styled Typography</Typography>
          <p style={theme.typography.body1}>my custom user content - how can i style this like above?</p>
        </>
      )
    }
票数 1
EN

Stack Overflow用户

发布于 2021-11-12 15:41:32

如果要在自定义组件中添加sx属性:

代码语言:javascript
复制
const P = styled("p")({});
代码语言:javascript
复制
const theme = useTheme()
代码语言:javascript
复制
<P sx={{ ...theme.typography.body1 }}>

如果要使用系统属性:

代码语言:javascript
复制
import { unstable_extendSxProp as extendSxProp } from "@mui/system";

const Psx = styled("p")();

function P(inProps) {
  const { sx, ...other } = extendSxProp(inProps);
  return <Psx sx={sx} {...other} />;
}
代码语言:javascript
复制
<P {...theme.typography.body1}>

如果您想像在Typography中一样使用variant属性

代码语言:javascript
复制
const T = styled('p')(({ theme, variant = 'body1' }) => ({
  ...theme.typography[variant],
}));
代码语言:javascript
复制
<T variant="h3">

实时演示

相关答案

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69941419

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档