旺仔小糖

styled-components a year ago

react
css
1644个字符
共有107人围观

styled-components 可以让你在js中随意发挥css, 正如下面官网所言, 你可以随意使用css,包括媒体查询,伪类选择器,样式嵌套(like sass)

# install
npm install styled-components

一个简单的Button

import styled from 'styled-components'

const Button = styled.button`
  background: transparent;
  border-radius: 3px;
  border: 2px solid #BF4F74;
  color: #BF4F74;
  margin: 0 1em;
  padding: 0.25em 1em
`

这个Button变量现在就是一个react组件, styled.button后面是模版字符串

模版字符串:

模版字符串里你可以调用方法

如果没有传递插值,则函数接收的第一个参数是一个包含字符串的数组。

// These are equivalent:
fn`some string here`;
fn(['some string here']);

一旦传递了插值,数组就会包含传递的字符串,并在插值的位置进行拆分。其余参数将按顺序为插值。

const aVar = 'good';


// These are equivalent:
fn`this is a ${aVar} day`;
fn(['this is a ', ' day'], aVar);

这有点麻烦,但这意味着我们可以在样式化组件中接收变量、函数或 mixins(css 助手),并将其展平为纯 CSS。

说到展平,styled-components 会忽略插值为undefinednullfalse 或空字符串 (""),这意味着你可以自由的使用短路运算符来有条件地添加 CSS 规则。

# 如果A为假 后面就不用计算了
A && expr

向Button传递参数

import styled, { css } from 'styled-components'


const Button = styled.button<{ $primary?: boolean; }>`
  background: transparent;
  border-radius: 3px;
  border: 2px solid #BF4F74;
  color: '#BF4F74';
  margin: 0 1em;
  padding: 0.25em 1em;


  ${props =>
    props.$primary &&
    css`
      background: '#BF4F74';
      color: white;
    `};
`

优秀文章