Tailwind 过渡延迟任意值仅适用于特定值

Tailwind transition delay arbitrary value only working for specific values

我的行为与 tailwinds 任意值功能非常不一致,特别是与转换延迟相关 属性。当我直接在任意值内使用任何随机值时,它适用于我目前测试过的每个值(随机正整数)。例如...

<li className="delay-[2455]">{some text}</li>

但是如果我要使用一个变量,class 只会偶尔产生影响,这取决于值,看起来是随机的。例如...

const delay = "250ms";
return <li className={`delay-[${delay}]}`></li>

上面的这个片段将产生一个有效的 class 但下面的片段将没有效果并且不会产生一个有效的 class

const delay = "500ms";
return <li className={`delay-[${delay}]}`></li>

我不确定这是我做错了什么,还是顺风的一些奇怪的怪癖。我愿意接受任何和所有的建议。如果它有所作为,我将 typescript 与 react 结合使用。 我正在使用 tailwindcss 版本 3.0.11 和 postcss 版本 8.4.5 这些是我的 tailwind.config.js 和我的 postcss.config.js 文件

module.exports = {
  content: ["./src/**/*.{js,jsx,ts,tsx}",],
  theme: {
    extend: {
      screens: {
        '3xl': '1920px',
        'xsm': '428px',
        '2xsm': '360'
      },
      fontFamily: {
        title: ['Patrick Hand'],
        body: ['Balsamiq Sans']
      },
      transitionProperty: {
        'opacity': 'opacity',
      },
    },
  },
  plugins: [],
}

module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
}

直接来自文档:

The most important implication of how Tailwind extracts class names is that it will only find classes that exist as complete unbroken strings in your source files.

If you use string interpolation or concatenate partial class names together, Tailwind will not find them and therefore will not generate the corresponding CSS

这意味着您需要使用完整的 class 名称,而不是其各部分的动态连接。

例如,您可以创建这样的函数:

function getClassByDelay(delay) {
  return {
    250: 'delay-250',
    500: 'delay-500',
    750: 'delay-750',
  }[delay]
}

然后像这样使用它:<li className={getClassByDelay(delay)}></li>

如果你真的需要使用动态 classes 那么你也可以使用另一种方法:只需将它们添加到配置中的 safelist 数组中:

// tailwind.config.js
module.exports = {
  content: [
    // ...
  ],
  safelist: [
    'delay-250',
    'delay-500',
    'delay-750',
    // etc.
  ]
  // ...
}

这样 Tailwind 就会知道它无论如何都需要生成这个 safelist classes,不管它是否在您的源代码中找到它们。

显然它有一个缺点,你需要管理这个列表并且不要忘记从配置中删除未使用的 classes 如果你停止在代码中使用它们,否则它们将成为你的包中的负担.

更多信息:https://tailwindcss.com/docs/content-configuration#class-detection-in-depth