react css组织的另一种选择styled-components

  • 2019 年 12 月 4 日
  • 笔记

写 React 的同学肯定纠结过 CSS 该怎么组织的问题。传统 WEB 开发里面推崇的 CSS、JS、HTML 关注点分离不建议把 CSS 写到 JS 里面,随着开发方式的演化,这种写法总会让人觉得很别扭,因为从概念上来讲组件要具有封装、自治的特点,那么把 CSS 写到组件里面会更容易维护,也能把 JS 的功能发挥到极致,styled-components 就是这样一个库,让你很容的用 CSS 创建比较纯粹的样式组件.话不多说,直接上代码.

基本用法

const Title = styled.h1`    font-size: 1.5em;    text-align: center;    color: palevioletred;    &:hover {      color: green;      }  `;  <Title>Hello World, this is my first styled component!</Title>

是不是有种似曾相识感觉?(类似rn 的写法). 也就是说,styled-components 的 css 仍然还是css,动画也不成问题:

const rotate360 = keyframes`    from {      transform: rotate(0deg);    }      to {      transform: rotate(360deg);    }  `;    const Rotate = styled.div`    display: inline-block;    animation: ${rotate360} 2s linear infinite;  `;

传递 props

const Button = styled.button`    background: ${props => props.primary ? 'palevioletred' : 'white'};    color: ${props => props.primary ? 'white' : 'palevioletred'};    border: 2px solid palevioletred;    border-radius: 3px;  `;    <Button primary>Primary</Button>

第三方组件

import styled from 'styled-components';  import { Link } from 'react-router';    const StyledLink = styled(Link)`    color: palevioletred;    display: block;    margin: 0.5em 0;    font-family: Helvetica, Arial, sans-serif;      &:hover {      text-decoration: underline;    }  `;  <StyledLink to="/">This Link is styled!</StyledLink>

目前支持的dom元素

export default [ 'a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr',

// SVG 'circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan', ]

就是这么简单, styled-components 的联合创造者Max Stoiber说:

styled-components 的基本思想就是通过移除样式和组件之间的映射关系来达到最佳实践.

使用styled-components 几乎是零学习成本的切换,存在疑惑也很容易切换会你所熟悉的领域.一个比较明显的缺陷是层级关系的样式没能很好的解决,需要通过其他办法处理.期待即将到来的 v2.0 能够有更好的表现.