【问题标题】:styled-components - how to set styles on html or body tag?styled-components - 如何在 html 或 body 标签上设置样式?
【发布时间】:2018-03-27 09:59:59
【问题描述】:

通常,当使用纯 CSS 时,我有一个样式表,其中包含:

html {
    height: 100%;
}

body {
    font-size: 14px;
}

在我的 React 项目中使用 styled-components 时,如何设置 html 或 body 标签的样式?我是否为此目的维护一个单独的 CSS 文件?

【问题讨论】:

    标签: reactjs styled-components jss


    【解决方案1】:

    当然,您可以通过<link> 标记维护一个单独的 CSS 文件,将其包含在 HTML 中。

    对于v4:

    使用 Styled-components 中的 createGlobalStyle。

    import { createGlobalStyle } from 'styled-components'
    
    const GlobalStyle = createGlobalStyle`
      body {
        color: ${props => (props.whiteColor ? 'white' : 'black')};
      }
    `
    
    <React.Fragment>
      <GlobalStyle whiteColor />
      <Navigation /> {/* example of other top-level stuff */}
    </React.Fragment>
    

    前v4:

    Styled-components 还导出一个 injectGlobal 帮助器以从 JavaScript 注入全局 CSS:

    import { injectGlobal } from 'styled-components';
    
    injectGlobal`
      html {
        height: 100%;
        width: 100%;
      }
    `
    

    请参阅API documentation 了解更多信息!

    【讨论】:

    • 看这个你只能硬编码 HTML 和 BODY 元素。如果您想在 BODY 元素上允许不同的背景颜色,您将如何动态设置它们?
    • 应该补充一点,使用全局样式的正确方法不是将组件包装在其中,而是将其称为独立组件。
    【解决方案2】:

    截至 2018 年 10 月。

    注意

    injectGlobal API 被移除并替换为 createGlobalStyle 样式组件 v4。

    根据文档createGlobalStyle 是

    一个辅助函数,用于生成处理全局样式的特殊 StyledComponent。通常,样式化的组件会自动限定为本地 CSS 类,因此与其他组件隔离。在 createGlobalStyle 的情况下,此限制被移除,并且可以应用 CSS 重置或基本样式表等内容。

    示例

    import { createGlobalStyle } from 'styled-components'
    
    const GlobalStyle = createGlobalStyle`
      body {
        color: ${props => (props.whiteColor ? 'white' : 'black')};
      }
    `
    
    // later in your app
    
    <React.Fragment>
      <Navigation /> {/* example of other top-level stuff */}
      <GlobalStyle whiteColor />
    </React.Fragment>
    

    阅读更多关于official docs。

    【讨论】:

      【解决方案3】:

      如果你使用material-UI,那么你不需要styled-components来实现这个。您可以简单地覆盖 theme.js 文件中设置的默认背景:

      overrides: {
        palette: {
          background: {
            default: "#fff"
          }
        }
      }
      

      然后你只需要将你的根组件包装在Material-UI CssBaseLine component:

      <MuiThemeProvider theme={muiTheme}>
        <CssBaseline />
        <App />
      </MuiThemeProvider>
      

      那个基线组件sets the default background on the &lt;body&gt; element。

      也看过这个问题:https://github.com/mui-org/material-ui/issues/10764

      【讨论】:

        猜你喜欢
        • 2018-09-06
        • 2020-08-18
        • 2020-04-04
        • 2019-07-15
        • 2018-07-11
        • 2020-05-01
        • 2021-07-16
        • 2021-11-04
        • 2018-11-12
        相关资源
        最近更新 更多