javascript - 设计系统 : styles override using TailwindCSS

标签 javascript css reactjs tailwind-css

我正在尝试使用 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>
  );
}
这是显示的内容:
preview
一些属性被覆盖,如 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/

相关文章:

javascript - 使用 Flexbox 的最小和最大高度

javascript - React 受控组件与不受控组件的总体定义

javascript - 如何将包含数组对象的对象字符串化?

javascript - iPhone X 网站安全区

javascript - 使用 jquery 显示和隐藏叠加层

javascript - 检测 JavaScript 中的不可打印字符

javascript - 从 requirejs 迁移到 webpack

javascript - 特定尺寸屏幕的 CSS(在我的例子中是 iframe)

javascript - 无法渲染父 Prop

php - 单击该行时将所选类添加到表行