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

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

  • 写好props类型,props的数量决定组件的自由度
  • 没了

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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;