Styled-Component

安装

npm install --save styled-components

创建样式组件

创建组件

1
2
import styled from 'styled-components'
const Button = styled.button``

一般的样式

1
2
3
4
5
6
7
8
const Button = styled.button`
  background: transparent;
  border-radius: 3px;
  border: 2px solid palevioletred;
  color: palevioletred;
  margin: 0 1em;
  padding: 0.25em 1em;
`

读取组件参数

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const Button = styled.button`
  background: transparent;
  border-radius: 3px;
  border: 2px solid palevioletred;
  color: palevioletred;
  margin: 0 1em;
  padding: 0.25em 1em;

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

子选择器

1
2
3
4
5
6
7
8
const Text = styled.p`
  font-size: 12px;
  color: blue;
  &:nth-child(3) {
    margin-bottom: 20px;
    color: red !important;
  }
`

使用组件

可以作为普通组件使用

1
2
3
4
5
function Demo() {
  return (
    <Button />
  )
}
updatedupdated2022-08-222022-08-22