styled-components 是一个常用的 css in js 类库。和所有同类型的类库一样,通过 js 赋能解决了原生 css 所不具备的能力,比如变量、循环、函数等。
优点:
贯彻React的 everything in JS理念,降低js对css⽂件的依赖
组件的样式和其他组件完全解耦,有效避免了组件之间的样式污染
1、安装
yarn add styled-components
yarn add @types/styled-components -D
2、配置
如果不配置会提示找不到模块“styled-components”的声明文件
在根目录src下新建 styledComponents.d.ts
内容如下:
declare module 'styled-components';
3、使用
示例1
Demo.tsx
import React from 'react'
import styled from 'styled-components'
import IconSetting from '../../assets/imgs/icon-setting.png'
const DemoButtonStyled = styled.button`
border: none;
outline: none;
background-color: #f00;
color: #fff;
margin: 0;
min-width: 100px;
height: 40px;
line-height: 40px;
text-align: center;
font-size: 14px;
border-radius: 4px;
cursor: pointer;
&:hover{
opacity: .5;
}
`
// 携带参数
const IconSettingStyled = styled.img<{size:string}>`
width: ${({ size }) => size};
height: ${({ size }) => size};
`
export default () => {
return (
<div>
<DemoButtonStyled> 测试Button </DemoButtonStyled>
<IconSettingStyled src={IconSetting} size="14px" />
</div>
)
}
示例二
// 判断是否禁用
const isDisabledStyle = false;
const DemoButtonStyled = styled.button`
border: none;
outline: none;
background-color: #f00;
color: #fff;
margin: 0;
min-width: 100px;
height: 40px;
line-height: 40px;
text-align: center;
font-size: 14px;
border-radius: 4px;
cursor: pointer;
&:hover{
opacity: .5;
}
&:disabled{
background-color: ${()=> isDisabledStyle && 'gray'};
color: ${(props:any) =>props.disabled ? 'black' : '#fff'};
cursor: unset;
&:hover{
opacity: unset;
}
}
`
export default () => {
return (
<DemoButtonStyled disabled={isDisabledStyle}> 测试Button </DemoButtonStyled>
)
}
散会…
本文介绍了styled-components库如何通过JavaScript增强CSS能力,如变量、循环和函数,并阐述其优点,包括React的组件化风格和样式解耦。通过示例展示如何安装配置和实际使用,包括带参数的样式和条件样式应用。
268

被折叠的 条评论
为什么被折叠?



