简体   繁体   English

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

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

I want to know if there is a possibility to cast styles from styled-components to wrapping element, like <body> tag in the way that looks like this:我想知道是否有可能将样式从styled-components为包装元素,例如<body>标记,如下所示:

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

As it turns out - you can't set styled components to outer elements.事实证明 - 您不能将样式组件设置为外部元素。 This violates the philosophy of encapsulation - a benefit from styled-components .这违反了封装的哲学 - 来自styled-components的好处。

So the way to do this would be to add a new class to body element called classList via JS in the parent component with componentDidMount() and remove it with componentWillUnmount() .因此,要做到这一点的方法是将一个新类添加到body称为元素classList通过JS在父组件与componentDidMount()并删除其与componentWillUnmount()

No, but you can use the global inject function to set stuff on your body like this:不,但您可以使用全局注入功能在您的身体上设置如下内容:

import { injectGlobal } from 'styled-components';

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

  body {
    margin: 0;
  }
`;

The example is from here: https://www.styled-components.com/docs/api#injectglobal示例来自此处: https : //www.styled-components.com/docs/api#injectglobal

I think you can't do that.我认为你不能那样做。

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

So,when you put <SomePageWrapper/> in the render,it turns to be <body></body> .Then you need to put it in the root part,to replace <body> .所以,当你把<SomePageWrapper/>放在渲染中时,它变成了<body></body> 。然后你需要把它放在根部分,替换<body>

But how do you replace the <body> you have in index.html .When you can't replace it,you will end up two <body> in browser,or something weird will happen.但是你如何替换你在index.html<body> 。当你不能替换它时,你最终会在浏览器中出现两个<body> ,否则会发生一些奇怪的事情。

Just simply use css file for只需简单地使用 css 文件

For v4 styled-components, use createGlobalStyle .对于 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM