初识👀Styled-Component

96 阅读1分钟

1、简介

Styled-Components 文档

它有几个特点:使用模板字符串标签+样式组合后是一个大写字母开头表示的组件,比如可以说是将react开发中最流行的一些写法整合起来,对于React开发者来说,是非常好入手的。那么,在react组件中,使用外部css还是组件css,不同的开发者习惯不同。支持外部css的人,认为:组件是jsx,应该和css分离,保证组件的纯净外部css也可以有很好的管理方式命名空间的问题只要制定规范化的样式命名管理,就可以避免可以提取可复用的样式进行管理

2、安装

# with npm
npm install styled-components

# with yarn
yarn add styled-components

#with pnpm
pnpm add styled-components

:::info In package.json: :::

"styled-components": "^5"

3、常用用法

3.1、标签

import styled from 'styled-components'


// 给button标签添加样式
export const Button = styled.button`
width:200px;
height:100px;
background: teal;
`

render(
  <>
    <Button>按钮</Button>
  </>
)

3.2、继承


// 继承Button里面的所有css样式
export const ButtonGroup = styled(Button)`
	color: teal;
`

3.3、属性

export const Input = styled.input.attrs({
  value:props =>props.value,
  name: 'username',
  placeholder:'请输入用户名称'
})`
	width:100px;
  height:32px;
  border:1px solid #efefef;
  border-radius: 4px;
`

3.4、背景图引入

import bg_img from '@/asstes/img/bg_img.png'

export const BaseWrapper = styled.div`
	width:100%;
  height:100%;
  background: url(${bg_img}) no-repeat;
`

3.5、参数

import { MainWrapper } from './style.ts'

render(){

  return (
    <MainWrapper isShow={true} height={'200px'}></MainWrapper>
  )
}


// style.ts

interface IStyle {
	isShow: Boolean,
  height: String
}

export const MainWrapper = styled.div<IStyle>`
	display: ${props.isShow ? 'block': 'none};
  height: ${props.height}
`