【问题标题】:MakeStyles (Material UI) apply style to child elementMakeStyles (Material UI) 将样式应用到子元素
【发布时间】:2021-01-26 02:38:57
【问题描述】:

我想知道是否可以使用MakesStyles 仅将样式应用于子元素,例如在普通的 HTML/CSS 项目中:

<div className="parent">
  <h1>Title!</h1>
</div>
.parent h1 {
  color: #f00;
}

这将为 div 中的每个标题着色。
我尝试了几种不同的方法,其中一种是:

// Function
const { parent } = homeStyle()

return (
  <div className={parent}>
    <h1>Title!</h1>
  </div>
)

// Style
const homeStyle = makeStyles(theme => ({
  parent: {
    background: "#fff",
    h1: {
      color: "#f00",
    }
  },
}))

但是没有用。

【问题讨论】:

    标签: reactjs typescript material-ui


    【解决方案1】:

    如果您只想设置 material-ui H1 标题的样式,您可以选择它:

    .parent .MuiTypography-h1 {
      color: #f00;
    }
    
    

    在下图中的替代解决方案中,您将看到使用 material-ui 应用于元素的类。检查器可以方便地识别您要选择的材料 UI 元素的名称。

    您的里程可能会有所不同,具体取决于您的 CSS 设置。


    但是,我从您的问题中了解到,希望在 &lt;div&gt; amonst 其他样式的 H1 中选择单个 H1。这可以通过 material-ui 库中的ThemeProvider (docs here) 来完成:

    import { Typography } from "@material-ui/core";
    import {
      createMuiTheme,
      responsiveFontSizes,
      ThemeProvider
    } from "@material-ui/core/styles";
    
    const Themed = ({ children }) => {
      const theme = createMuiTheme({
        overrides: {                          {/* <--  create a style override */}
          MuiTypography: {
            h1: {
              "&.styled": {         {/* <-- specify a className for overrides */}
                color: "red"
              }
            }
          }
        }
      });
    
      return (
        <ThemeProvider theme={responsiveFontSizes(theme)}>
          <>{children}</>
        </ThemeProvider>
      );
    };
    
    const App = () => {
      return (
        <Themed>
    
          <Typography 
            className="styled"               {/* <-- add the style from above */}
            variant="h1"> 
    
            Styled H1
    
          </Typography>
    
          <Typography 
            variant="h1">
    
            Not styled H1
    
          </Typography>
    
          <Typography 
            variant="h1">
    
            Me neither
    
          </Typography>
    
        </Themed>
      );
    };
    
    export default App;
    
    

    工作CodeSandbox

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-16
      • 2020-03-31
      • 2020-07-07
      • 2021-05-06
      • 2021-12-29
      • 2020-01-07
      • 2023-03-23
      相关资源
      最近更新 更多