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

Github

https://github.com/xxxxue/nextjs-antd-demo

你可能感兴趣的:(JavaScript,react.js,typescript,cssinjs,next.js,cra)