介绍
styled-components是一个针对React的 css in js 类库
(官方文档戳这里)
它的优点在于:
- 贯彻React的 everything in JS理念,降低js对css文件的依赖
- 组件的样式和其他组件完全解耦,有效避免了组件之间的样式污染
引入和使用
安装
npm install --save styled-components
全局样式
在src目录下新建 style.js
通过createGlobalStyle这个API将全局样式导出
(这里使用的是 Reset.css)
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‘) );
局部(组件)样式
对于一个特定的组件,我们可以事先在render函数中,用组件的命名方式替换原本的div等标签
import React, {Component} from ‘react‘ import { HeaderWrapper, Nav, NavItem } from ‘./style‘ class Header extends Component { render() { return ( <HeaderWrapper> <Nav> <NavItem className=‘left active‘>首页</NavItem> <NavItem className=‘left‘>下载App</NavItem> <NavItem className=‘right‘>登陆</NavItem> <NavItem className=‘right‘> <span className=‘iconfont‘></span> </NavItem> </Nav> </HeaderWrapper> ) } } export default Header
然后在同目录下的style.js中编写具体的CSS样式,以组件名的形式导出
import styled from ‘styled-components‘ export const HeaderWrapper = styled.div` position: relative; margin: 0; padding: 0; height: 58px; border-bottom: 1px solid #f0f0f0 `; export const Nav = styled.div` width: 945px; height: 100%; padding-right: 70px; box-sizing: border-box; margin: 0 auto; ` export const NavItem = styled.div` line-height: 56px; padding: 0 15px; font-size: 17px; color: #333; `
转:https://www.jianshu.com/p/9c7b0b36b55f