最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

I want to know if there is a possibility to cast styles from styled-ponents to wrapping element, like <body> tag in the way that looks like this:

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

I want to know if there is a possibility to cast styles from styled-ponents to wrapping element, like <body> tag in the way that looks like this:

class SomePageWrapper = styled.div`
  body {
    font-size: 62.5%
  }
`
Share Improve this question asked Dec 28, 2017 at 14:41 zmiizmii 4,3173 gold badges43 silver badges69 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

No, but you can use the global inject function to set stuff on your body like this:

import { injectGlobal } from 'styled-ponents';

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

  body {
    margin: 0;
  }
`;

The example is from here: https://www.styled-ponents./docs/api#injectglobal

As it turns out - you can't set styled ponents to outer elements. This violates the philosophy of encapsulation - a benefit from styled-ponents.

So the way to do this would be to add a new class to body element called classList via JS in the parent ponent with ponentDidMount() and remove it with ponentWillUnmount().

For v4 styled-ponents, use createGlobalStyle .

import { createGlobalStyle } from 'styled-ponents'

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>

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>.

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.

Just simply use css file for

发布评论

评论列表(0)

  1. 暂无评论