注:在styled-component V4版本中injectGlobal API除去,取而代之的是createGlobalStyle样式组件。
也就是说以前的 injectGlobal 全局样式在V4版本代替为使用 createGlobalStyle 渲染组件的方式来使用全局样式。
官方文档说明(地址:https://www.styled-components.com):
A helper method to write global CSS. It does not return a component, but adds the styles to the stylesheet directly.
ARGUMENTS | DESCRIPTION |
---|---|
1. TaggedTemplateLiteral | A tagged template literal with your global styles inside. |
import { injectGlobal } from 'styled-components'
injectGlobal`
@font-face {
font-family: "Operator Mono";
src: url("../fonts/Operator-Mono.ttf");
}
body {
margin: 0;
}
`
We do not encourage the use of this. Try to use it once per app at most, if you must, contained in a single file. This is an escape hatch. Only use it for the rare @font-face definition or body styling.
createGlobalStyle 官方说明:
A helper function to generate a special StyledComponent that handles global styles. Normally, styled components are automatically scoped to a local CSS class and therefore isolated from other components. In the case of createGlobalStyle, this limitation is removed and things like CSS resets or base stylesheets can be applied.
ARGUMENTS | DESCRIPTION |
---|---|
1. TaggedTemplateLiteral | A tagged template literal with your CSS and interpolations. |
Returns a StyledComponent that does not accept children. Place it at the top of your React tree and the global styles will be injected when the component is "rendered".
import { createGlobalStyle } from 'styled-components'
const GlobalStyle = createGlobalStyle`
body {
color: ${props => (props.whiteColor ? 'white' : 'black')};
}
`
// later in your app
{/* example of other top-level stuff */}
Since the GlobalStyle component is a StyledComponent, that means it also has access to theming from the component if provided.
import { createGlobalStyle, ThemeProvider } from 'styled-components'
const GlobalStyle = createGlobalStyle`
body {
color: ${props => (props.whiteColor ? 'white' : 'black')};
font-family: ${props => props.theme.fontFamily};
}
`
// later in your app
{/* example of other top-level stuff */}
实例测试:
style.js :
import {createGlobalStyle} from 'styled-components';
export const GlobalStyle = createGlobalStyle`
body {
background: blue;
}
`;
App.js:
import React, { Component,Fragment } from 'react';
import Header from "./common/header";
//导入样式文件
import {GlobalStyle} from "./style";
class App extends Component {
render() {
return (
)
}
}
export default App;
做的不好,仅供参考!