styled-components解决全局样式'injectGl

2019-08-22  本文已影响0人  景元合

前言

在使用styled-components最新版时候引入injectGlobal生成全局样式时候报错,主要是此方法已废除,取而代之的是createGlobalStyle()。

createGlobalStyle()用法

1.在样式文件中引入createGlobalStyle,代码如下:

import {createGlobalStyle} from 'styled-components'
export const Globalstyle=createGlobalStyle`
body {
  margin: 0;
  background:#f00;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
    "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}
`

2.在需要使用样式的组建中引入刚刚定义的 GlobalStyle ,然后将 <GlobalStyle /> 组件放在 render() 中最外层元素下面:

import React from 'react';
import { Globalstyle } from './style.js';
function App() {
  return (
    <fragment>
      <Globalstyle></Globalstyle>
      <div>hello world</div>
    </fragment>
    
  );
}
export default App;

像这样引用好之后,就可以正常使用全局变量啦。

上一篇下一篇

猜你喜欢

热点阅读