styled-components解決全局樣式'injectGlobal' 廢除的問題

前言

在使用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;

像這樣引用好之后,就可以正常使用全局變量啦。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容