React styled-components TypeScript 的最佳实践

styled-components + TypeScript

需要安装 @types
yarn add -D @types/styled-components

详细说明

原生dom使用 styled.div , styled.h1

  • Button 是 antd 的按钮

IMyButtonProps 是props的ts类型定义,

  • attrs需要指定一次, 普通css开头也需要指定一次

attrs 是 设置属性

  • 一般用来封装通用的属性, 不通用的就在jsx中直接传入,
    可以直接传入对象,也可以传入匿名方法最后返回对象

$myColor / $myBorderColor 是 props

  • $开头代表是 Transient props (v5.1新增),
    框架会自动过滤掉,不会传递给React组件,不是标准dom的属性名输出到html中会报错

border-radius: 10px; 是设置style,

  • props 方法中可以返回 字符串(无智能提示) 或 CSSProperties (有智能提示)

代码

import { Button } from 'antd';
import { NextPage } from 'next';
import { memo } from 'react';
import styled from 'styled-components';

interface IMyButtonProps {
    $switchShape: boolean;
    $myColor: string;
    $myBorderColor: string;
}

let MyButton = styled(Button).attrs<IMyButtonProps>((props) => {
    // console.log(props);
    
    let myShape = props.$switchShape ? 'circle' : 'round';
    
    return { type: 'primary', shape: myShape };
    
})<IMyButtonProps>`

    margin-left: 10px;
    
    ${{
        padding: '100px',
    }}
    
    ${(props) => {
        // 可以获取到 attrs 中的结果
        // console.log(props);

        // 返回字符串
        return `
            color:${props.$myColor}
        `;
    }};

    ${(props) => {
        // 返回 react CSSProperties 对象
        return {
            borderColor: props.$myBorderColor,
        };
    }};
`;

interface IProp {}
let index: NextPage<IProp> = function (props) {
    return (
        <>
            <Button style={{ borderRadius: '20px' }} type='primary'>
                click 1
            </Button>

            <MyButton ghost={true} $switchShape $myBorderColor='black' $myColor='red'>
                click 2
            </MyButton>
        </>
    );
};

export default memo(index);
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值