跳转到内容

写组件库,从第一个按钮开始编

发布于:

写一个组件?就我现在知道的事,应该分这几点

感觉无非就是先写一下interface,然后当作props传入组件就行了

比如我这个按钮,当然,简单的组件并不能说明什么,那些日历什么的倒真是麻烦得不行

import React from "react";
import classNames from "classnames";

export interface ButtonProps {
  title?: string;
  variant?: "outlined" | "contained";
  onClick?: () => void;
  children?: React.ReactNode;
  disabled?: boolean;
  size?: "small" | "medium" | "large";
  rounded?: "none" | "small" | "medium" | "large";
  icon?: React.ReactNode;
  iconPosition?: "left" | "right";
}


function Button(props: ButtonProps) {
  const {
    title,
    onClick,
    children,
    variant = "contained",
    disabled,
    size = "medium",
    rounded = "small",
    icon,
    iconPosition = "left"
  } = props;


  return (
    <button
      onClick={onClick}
      className={classNames("px-2 cursor-pointer shadow-none text-sm", {
        "border-2 border-solid border-black bg-white text-black":
          variant === "outlined",
        " bg-black text-white border-none": variant === "contained",
        "pointer-events-none  cursor-not-allowed pointer-event-none bg-gray-300 border-none ":
          disabled,
        "h-8": size === "small",
        "h-10": size === "medium",
        "h-12": size === "large",
        "rounded-none": rounded === "none",
        "rounded-sm": rounded === "small",
        "rounded-md": rounded === "medium",
        "rounded-lg": rounded === "large",
        "flex gap-3 items-center":icon,
        "flex-row-reverse":icon && iconPosition === "right"
      })}
    >
      {icon && icon}
      {title || children}
    </button>
  );
}
export default Button;