在React中,怎么用tailwind css(就叫顺丰吧 :D 。。。)封装Button组件

我的目的

想用 tailwind css 来快速封装Button组件,而不是从更大型的UI库导入一个Button组件(那样就太大材小用)。

几个工具

开抄

//Button.tsx

import React, { ReactElement, ReactNode } from "react";
import { ButtonType, ButtonSize, buttonSize, buttonType } from "./theme";

interface Props {
  children?: ReactNode;
  size: buttonSize;
  type: buttonType;
}

export default function Button({ children, size, type }: Props): ReactElement {
  const classNames = `${ButtonType[type]} ${ButtonSize[size]}`;
  return <button className={classNames}>{children}</button>;
}

//theme.ts 东西有点多,因为是用血轮眼复制过来的。。。

export const ButtonType = {
  primary:
    "tw-inline-block tw-px-6 tw-py-2.5 tw-bg-blue-600 tw-text-white tw-font-medium  tw-leading-tight tw-uppercase tw-rounded tw-shadow-md hover:tw-bg-blue-700 hover:tw-shadow-lg focus:tw-bg-blue-700 focus:tw-shadow-lg focus:tw-outline-none focus:tw-ring-0 active:tw-bg-blue-800 active:tw-shadow-lg tw-transition tw-duration-150 tw-ease-in-out ",
  secondary:
    "tw-inline-block tw-px-6 tw-py-2.5 tw-bg-purple-600 tw-text-white tw-font-medium  tw-leading-tight tw-uppercase tw-rounded tw-shadow-md hover:tw-bg-purple-700 hover:tw-shadow-lg focus:tw-bg-purple-700 focus:tw-shadow-lg focus:tw-outline-none focus:tw-ring-0 active:tw-bg-purple-800 active:tw-shadow-lg tw-transition tw-duration-150 tw-ease-in-out",
  basic:
    "tw-inline-block tw-px-6 tw-py-2.5 tw-bg-green-500 tw-text-white tw-font-medium  tw-leading-tight tw-uppercase tw-rounded tw-shadow-md hover:tw-bg-green-600 hover:tw-shadow-lg focus:tw-bg-green-600 focus:tw-shadow-lg focus:tw-outline-none focus:tw-ring-0 active:tw-bg-green-700 active:tw-shadow-lg tw-transition tw-duration-150 tw-ease-in-out",
  delete:
    "tw-inline-block tw-px-6 tw-py-2.5 tw-bg-red-600 tw-text-white tw-font-medium  tw-leading-tight tw-uppercase tw-rounded tw-shadow-md hover:tw-bg-red-700 hover:tw-shadow-lg focus:tw-bg-red-700 focus:tw-shadow-lg focus:tw-outline-none focus:tw-ring-0 active:tw-bg-red-800 active:tw-shadow-lg tw-transition tw-duration-150 tw-ease-in-out",
};

export const ButtonSize = {
  sm: "tw-py-2 tw-px-4 tw-text-xs",
  lg: "tw-py-3 tw-px-6 tw-text-lg ",
};

export type buttonSize = keyof typeof ButtonSize;
export type buttonType = keyof typeof ButtonType;

就这样,喵。

posted @ 2023-01-24 18:20  刘老六  阅读(215)  评论(0编辑  收藏  举报