css - 如何使用 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;
}
}
是否已经发展出任何涵盖此内容的最佳实践?
解决方案
使用 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>
推荐阅读
- c++ - use QModelIndex to set background of a QTreeWidgetItem
- c++ - 使用 QMap 并获取编译错误消息
- upgrade - MarkLogic 升级和步骤
- android - 如何以编程方式检查 VoLTE 启用
- javascript - 如何从第三方 REST API 获取数据并显示在页面上
- java - 如何在java中将`List`更改为`List of tuple`
- javascript - uuid - 默认导出 (ReactJS - JavaScript)
- c - 如何使大容量存储设备从固件只读到 Windows
- c# - 从基类实例化特定类型的派生类属性
- php - Laravel Blade 变量范围