styled-components相关知识点

98 阅读1分钟

styled-components是一个针对React的 css in js 类库

优点:

  • 贯彻React的 everything in JS理念,降低js对css文件的依赖
  • 组件的样式和其他组件完全解耦,有效避免了组件之间的样式污染

使用: npm install --save styled-components 创建全局样式: 在src目录下新建 style.js 通过createGlobalStyle这个API将全局样式导出

import { createGlobalStyle } from 'styled-components'

export const GlobalStyle = createGlobalStyle`
  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;
  }
`;

然后在项目的入口文件(index.js)中
将其放在render函数的第一个html标签内部

import React, { Fragment } from 'react';
import ReactDOM from 'react-dom';
import { GlobalStyle} from './style';
import App from './App';

ReactDOM.render(
  <Fragment>
    <GlobalStyle/>
    <App/>
  </Fragment>,
  document.getElementById('root')
);

参考链接:

https://www.jianshu.com/p/9c7b0b36b55f  
https://www.jianshu.com/p/2d5f037c7df9  
https://github.com/hengg/styled-components-docs-zh