我是 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 示例)来注入(inject)全局样式:
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')
);
这显示了一个在主体上注入(inject)样式并为主体分配一个类的示例,该类可以稍后有条件地激活。
例如。
{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>
关于css - 如何使用 CSS-in-JS 方法设置 body 标签的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53795332/