【问题标题】:How can I force Tailwind to include a color?如何强制 Tailwind 包含颜色?
【发布时间】:2022-10-31 08:28:50
【问题描述】:

在我的一个 React 组件中,我收到了一个调色板名称,并想用它来更改我的组件中的颜色。

我的尝试:

    import { Link } from 'react-router-dom';
    
    export interface LinkModel {
      to: string;
      label: string;
      color?: string;
    }
    
    export const Alink = ({ to, label, color = 'primary' }: LinkModel) => {
      return (
        <div>
          <Link to={to} className={'font-medium text-' + color + '-600 hover:text-' + color + '-500'}>
            {label}
          </Link>
        </div>
      );
    };

我注意到,如果应用程序中的任何地方都不存在组合(例如text-primary-600),则它不会与样式捆绑在一起,并且我的链接也不会着色。

如何强制捆绑我的其他样式?

【问题讨论】:

标签: reactjs tailwind-css


【解决方案1】:

是的,Tailwind 没有检测到动态类名是正确的。

一种选择是将安全列表类添加到 Tailwind 配置中。 https://tailwindcss.com/docs/content-configuration#safelisting-classes

另一种选择是在代码中包含完整的类字符串。

这是通过添加具有所有组合的对象的一种可能方法。

const variantsLookup = {
  primary: 'font-medium text-slate-600 hover:text-slate-500',
  blue: 'font-medium text-blue-600 hover:text-blue-500',
  red: 'font-medium text-red-600 hover:text-red-500',
}

然后可以基于color 属性添加类。

<Link to={to} className={`${variantsLookup[color]}`}>
  {label}
</Link>

这个想法完全归功于西蒙。 https://www.protailwind.com/just-in-time-friendly-style-variants-in-tailwind-css-ui-components-part-1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-30
    • 1970-01-01
    • 2021-05-28
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    • 2020-11-10
    相关资源
    最近更新 更多