英文:
Tailwindcss + Nextjs problems with class + variables
问题
下午好,我需要帮助解决我在tailwindcss + nextjs中遇到的一个大问题...
问题是关于设置类时,我需要使用一个变量,类在CSS中已设置,但tailwind没有将类转换为样式。
我需要它像这样:
我已经尝试将类设置为常量,我尝试在组件内部和getstaticprops中都设置常量,但都没有起作用。
我尝试在CSS本身内部设置类,但也没有起作用。
英文:
Good afternoon, I need help with a big problem I'm having with tailwindcss + nextjs...
So the problem is when it comes to setting the classes, I need to use a variable, the class is set in the css, but the tailwind is not converting the class into a style.
I need it to be like this:
I already tried to set the class as constant, I tried to set the constant both inside the component and in getstaticprops, and none of them worked.
I've tried to set a class within the css itself and it didn't work either.
答案1
得分: 0
Tailwind 使用正则表达式来查找类名,因此它们需要作为不间断的字符串存在于您的源代码中。由此产生的一个后果是,您不能以您正在尝试的方式使用字符串插值,因为Tailwind 将无法找到类名。
相反,您可以将您的 props 映射到静态类名:
const Component = ({pokemon}) => {
const pokemonBgVariants = {
pikachu: 'bg-pokemontype-pikachu',
bulbasaur: 'bg-pokemontype-bulbasaur',
// ...
}
return (
<div className={`[...other classes] ${pokemonBgVariants[pokemon.types[0].type.name]}`}></div>
)
}
英文:
Tailwind uses regex to find class names, and because of this they need to exist as unbroken strings in your source code. A consequence of this is you cannot use string interpolation the way you're trying to do, as Tailwind will not be able to find the class name.
What you can do instead is map your props to static class names:
const Component = ({pokemon}) => {
const pokemonBgVariants = {
pikachu: 'bg-pokemontype-pikachu',
bulbasaur: 'bg-pokemontype-bulbasaur',
// ...
}
return (
<div className=`[...other classes] ${pokemonBgVariants[pokemon.types[0].type.name]}`></div>
)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论