我正在尝试使用 ReactJS 和 TailwindCSS 创建一个设计系统。
我创建了一个默认 Button
具有基本样式的组件如下:
import React from "react";
import classNames from "classnames";
const Button = React.forwardRef(
({ children, className = "", onClick }, ref) => {
const buttonClasses = classNames(
className,
"w-24 py-3 bg-red-500 text-white font-bold rounded-full"
);
const commonProps = {
className: buttonClasses,
onClick,
ref
};
return React.createElement(
"button",
{ ...commonProps, type: "button" },
children
);
}
);
export default Button;
然后我使用 Button
在我的页面中,例如:import Button from "../src/components/Button";
export default function IndexPage() {
return (
<div>
<Button onClick={() => console.log("TODO")}>Vanilla Button</Button>
<div className="h-2" />
<Button
className="w-6 py-2 bg-blue-500 rounded-sm"
onClick={() => console.log("TODO")}
>
Custom Button
</Button>
</div>
);
}
这是显示的内容:一些属性被覆盖,如
background-color
但有些不是(其余的)。原因是 TailwindCSS 提供的类是按照
bg-blue-500
的顺序编写的。放在 bg-red-500
之后,因此覆盖它。另一方面,自定义按钮中提供的其他类在基本按钮上的类之前编写,因此不会覆盖样式。TailwindCSS 会发生这种行为,但只要类顺序可以产生这种情况,其他任何样式方法都可能会发生这种行为。
您是否有任何解决方法/解决方案来启用这种定制?
这是完整的CodeSanbox如果需要的话。
最佳答案
一种方法是 extract classes从您的组件使用 Tailwind 的 @apply
在您的 components
层。
/* main.css */
@layer components {
.base-button {
@apply w-24 py-3 bg-red-500 text-white font-bold rounded-full;
}
}
// Button.js
const Button = React.forwardRef(({ children, className = "", onClick }, ref) => {
const buttonClasses = classNames("base-button", className);
// ...
);
这会将样式提取到新的 base-button
中。类,这意味着它们可以很容易地被您传递给 Button
的实用程序类覆盖。零件。
关于javascript - 设计系统 : styles override using TailwindCSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66572968/