【问题标题】:Apply MUI styles to non-MUI markup elements将 MUI 样式应用于非 MUI 标记元素
【发布时间】:2021-12-24 17:07:25
【问题描述】:

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

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

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

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>
    </>
  )
}

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    您需要导入您的主题。从那里您可以访问 body1 默认字体样式以应用于 p 元素。

    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>
        </>
      )
    }
    

    【讨论】:

    • 用户内容已经包含 &lt;p&gt; &lt;h1&gt; 或其他我无法用 React 修改的标记 - 充其量我可以将样式添加到它们的父级......有没有办法全局使所有&lt;p&gt;等标签继承theme.typography.body1
    • 除Typography 之外,您如何为其他元素执行此操作,例如Link 的样式?
    【解决方案2】:
    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>
            </>
          )
        }
    

    【讨论】:

      【解决方案3】:

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

      const P = styled("p")({});
      
      const theme = useTheme()
      
      <P sx={{ ...theme.typography.body1 }}>
      

      如果你想使用系统属性:

      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} />;
      }
      
      <P {...theme.typography.body1}>
      

      如果你想使用variantTypography 一样的属性:

      const T = styled('p')(({ theme, variant = 'body1' }) => ({
        ...theme.typography[variant],
      }));
      
      <T variant="h3">
      

      现场演示

      相关答案

      【讨论】:

        猜你喜欢
        • 2021-12-10
        • 2022-07-27
        • 2018-10-26
        • 2018-12-24
        • 1970-01-01
        • 2018-10-25
        • 1970-01-01
        • 2022-08-16
        • 2022-10-05
        相关资源
        最近更新 更多