我正在使用 React 18、nextjs 13 和 tailwindcss、postcss、autoprefixer
期望:点击按钮切换边框颜色和其他样式 行为:除边框颜色外的所有样式都会切换
问题:为什么边框颜色的行为与其他样式不同?
损坏的代码:
import Head from 'next/head'
import { useState } from 'react'
export default function Home() {
const [dark, darkSet] = useState(true)
function handleClick() {
darkSet((prev) => !prev)
}
const bgColor = 'bg-' + (dark ? 'black' : 'white')
const textColor = 'text-' + (dark ? 'white' : 'black')
const borderColor = 'border-' + (dark ? 'white' : 'black')
const borderStyle = 'border-' + (dark ? 'solid' : 'dashed')
return (
<>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</Head>
<main>
<div className={`flex min-h-screen min-w-screen `}>
<div
className={`${bgColor} ${textColor} border-8 ${borderStyle} ${borderColor}`}
>
Get started by editing
</div>
<button onClick={handleClick} className="h-8 bg-red-500">
theme
</button>
</div>
</main>
</>
)
}
最佳答案
改变
const bgColor = 'bg-' + (dark ? 'black' : 'white')
const textColor = 'text-' + (dark ? 'white' : 'black')
const borderColor = 'border-' + (dark ? 'white' : 'black')
const borderStyle = 'border-' + (dark ? 'solid' : 'dashed')
至
const bgColor = dark ? 'bg-black' : 'bg-white'
const textColor = dark ? 'text-white' : 'text-black'
const borderColor = dark ? 'border-white' : 'border-black'
const borderStyle = dark ? 'border-solid' : 'border-dashed'
说明:
是否建议在tailwind
中使用动态类
?
否
通常不建议在 tailwind-css
中使用动态类
,因为 tailwind
使用 tree-shaking
即任何未在源文件中声明的类不会在输出文件中生成。
因此,始终建议使用完整类名
根据[文档][1]
If you use string interpolation or concatenate partial class names together, Tailwind will not find them and therefore will not generate the corresponding CSS
没有解决办法吗?
是
作为最后的手段,Tailwind 提供[安全列表类别][2]。
Safelisting is a last-resort, and should only be used in situations where it’s impossible to scan certain content for class names. These situations are rare, and you should almost never need this feature.
您可以使用[正则表达式][3]使用pattern
包含您想要的所有颜色
注意:您也可以强制 Tailwind 创建变体
:
在tailwind.config.js
module.exports = {
content: [
'./pages/**/*.{html,js}',
'./components/**/*.{html,js}',
],
safelist: [
{
pattern: /bg-(red|green|blue|orange)/, // You can display all the colors that you need
variants: ['lg', 'hover', 'focus', 'lg:hover'], // Optional
},
],
// ...
}
关于javascript - 使用模板字符串的 tailwindcss 动态边框颜色不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74976622/