首页 > 解决方案 > 如何使用 CSS-in-JS 方法设置 body 标签的样式?

问题描述

我是 CSS-in-JS 和情感的初学者,并试图将一个 sass react 应用程序移植到情感上。从一开始我就已经遇到了不知道如何设置 body 标签样式的问题。

人们通常习惯document.body.style这样做吗?我在任何地方都找不到这个...

假设我想将以下代码移植到情感上,那将如何实现?

$bodyFillColor: rgb(218, 236, 236);

body {
  margin: 0;
  padding: 0;
  min-height: 100vh;
  max-width: 100vw;
  background-color: $bodyFillColor;
  .noScroll {
    overflow: hidden;
  }
}

是否已经发展出任何涵盖此内容的最佳实践?

标签: cssreactjssassemotioncss-in-js

解决方案


使用 Emotion,您可以设置一些东西,例如以下 create-react-app 示例,以注入全局样式:

import React from 'react';
import ReactDOM from 'react-dom';
import { Global, css } from '@emotion/core'

const bodyFillColor = `rgb(218,236,236)`;

class App extends React.Component {
  render() {
    return(
      <div>
        <Global
          styles={css`
            body {
              background: ${bodyFillColor};
              margin: 0;
              padding: 0;
              min-height: '100vh';
              max-width: '100vw';
            }
          `}
        />
        <Global
          styles={{
            'body.noScroll': {
                // Prevent scrolling; conditionally activate this
                // in subcomponents when necessary ...
                overflow: 'hidden',
            },
          }}
        />
      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

这显示了一个在主体上注入样式并为主体分配一个类的示例,该类可以在以后有条件地激活。

例如。

{this.state.activate && <Global styles={{`stylesetc`}}/>}

https://emotion.sh/docs/globals

选择

StyledComponents 使用 CSS-in-JS 方法,非常适合 React 应用程序。这是我过去直接从文档中使用的一种技术:

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>

推荐阅读