styled-components - 如何在html或body标签上设置样式?

Joe*_*dee 26 reactjs styled-components jss

通常,在使用纯CSS时,我有一个包含以下内容的样式表:

html {
    height: 100%;
}

body {
    font-size: 14px;
}
Run Code Online (Sandbox Code Playgroud)

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

mxs*_*tbr 52

当然,您可以通过<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>
Run Code Online (Sandbox Code Playgroud)

上一篇v4:

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

import { injectGlobal } from 'styled-components';

injectGlobal`
  html {
    height: 100%;
    width: 100%;
  }
`
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅API文档!


Mad*_*ari 18

截至2018年10月.

注意

已删除injectGlobal API,并由styled-components v4中的createGlobalStyle替换.

根据文档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>
Run Code Online (Sandbox Code Playgroud)

阅读官方文档的更多内容.