我可以将样式设置为来自样式化组件的文档正文吗?

Can I set styles to document body from styled-components?

我想知道是否可以将样式从 styled-components 转换为包装元素,例如 <body> 标签,如下所示:

class SomePageWrapper = styled.div`
  body {
    font-size: 62.5%
  }
`

事实证明 - 您不能将样式组件设置为外部元素。这违反了封装的理念——styled-components 的好处。

所以这样做的方法是在父组件中使用 componentDidMount() 添加一个新的 class 到名为 classListbody 元素并将其删除componentWillUnmount().

我认为你不能那样做。

class SomePageWrapper = styled.body`
  font-size: 62.5%
`

所以,当你把<SomePageWrapper/>放在render里面的时候,它变成了<body></body>。然后你需要把它放在根部分,来代替<body>

但是你如何替换你在 index.html 中的 <body>。当你不能替换它时,你将在浏览器中结束两个 <body>,或者一些奇怪的东西会发生了。

只需将 css 文件用于

不,但您可以使用全局注入功能在您的 body 上设置内容,如下所示:

import { injectGlobal } from 'styled-components';

injectGlobal`
  @font-face {
    font-family: 'Operator Mono';
    src: url('../fonts/Operator-Mono.ttf');
  }

  body {
    margin: 0;
  }
`;

例子来自这里:https://www.styled-components.com/docs/api#injectglobal

对于 v4 样式组件,使用 createGlobalStyle 。

import { createGlobalStyle } from 'styled-components'

const GlobalStyle = createGlobalStyle`
  body {
    color: ${props => (props.whiteColor ? 'white' : 'black')};
  }
`

// later in your app

<React.Fragment>
  <GlobalStyle whiteColor />
  <Navigation /> {/* example of other top-level stuff */}
</React.Fragment>