代码之家  ›  专栏  ›  技术社区  ›  JoeTidee

样式化组件-如何在html或正文标记上设置样式?

  •  66
  • JoeTidee  · 技术社区  · 8 年前

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

    html {
        height: 100%;
    }
    
    body {
        font-size: 14px;
    }
    

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

    3 回复  |  直到 6 年前
        1
  •  116
  •   brettinternet mxstbr    7 年前

    当然,您可以通过 <link> 标签

    对于 v4 :

    使用 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

    样式化组件还导出 injectGlobal 从JavaScript注入全局CSS的助手:

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

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

        2
  •  25
  •   Madan Bhandari    7 年前

    截至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
  •  -2
  •   Stiño    6 年前

    如果使用材质UI,则不需要 styled-components 为了实现这一点。您可以简单地覆盖主题中设置的默认背景。js文件:

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

    然后只需将根组件封装在 Material-UI CssBaseLine component :

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

    基线组件 sets the default background on the <body> element

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