三、react安装styled-components

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>
  )
}

散会…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值