【问题标题】:Why tailwind dynamic class is not present为什么顺风动态类不存在
【发布时间】:2022-07-29 18:39:29
【问题描述】:

我有最新的 nextjs + tailwind。这是我的顺风配置:

module.exports = {
    mode: "jit",
    content: [
        "./pages/**/*.{js,ts,jsx,tsx}",
        "./components/**/*.{js,ts,jsx,tsx}",
    ],
    theme: {
        extend: {},
    },
    plugins: [],
};

components 文件夹内,我有Test.js 的内容组件:

const colors = {
    orange: "bg-orange-100",
    blue: "bg-blue-100",
};

export default function Header() {
    function HeaderButton(props) {
        return <div className={`bg-red hover:${colors[props.color]}`}></div>;
    }
    return <HeaderButton color="orange">Test</HeaderButton>
}

bg-red 类存在,但在悬停时我得到类 bg-orange-100 并且它已从结果 css 中清除,因此没有结果。有什么问题?


所以我发现问题完全在于悬停。如果我只是以这种方式添加类名,它就可以了。不适用于悬停等修改器。

【问题讨论】:

  • Tailwind 的 postcss 会删除所有未使用的类。如果顺风不允许动态类名,这可能是一个限制
  • @AhsanKhan 我认为像这样的 js 变量中提到的类是一个“hack”,它告诉 postcss 不要删除它,因为它已被使用?
  • 我刚查了一下,顺风不建议这样做。检查:stackoverflow.com/questions/69687530/…
  • 也许可以尝试将其与hover:一起添加到js变量中

标签: javascript next.js tailwind-css


【解决方案1】:

正如顺风文档提到的https://v2.tailwindcss.com/docs/just-in-time-mode。他们建议我们不要像你做的那样动态生成类。

只需简单地理解,tailwind 会在编译时尝试理解您的类定义,以便清晰的声明将帮助tailwind 理解您打算在运行时执行的操作。

简单的例子可以帮助你更好地理解这一点:

<div className={`mt-[${size === 'lg' ? '22px' : '17px' }]`}></div>
// Tailwind don't know what kind of class to build
<div className={ size === 'lg' ? 'mt-[22px]' : 'mt-[17px]' }></div>
// Tailwind understand 'mt-[22px]' and 'mt-[17px]' to build

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 2021-08-24
    • 2019-03-02
    • 2021-04-17
    • 2022-01-18
    • 1970-01-01
    • 2022-11-01
    相关资源
    最近更新 更多