Tailwindcss + Nextjs问题与类 + 变量

huangapple go评论74阅读模式
英文:

Tailwindcss + Nextjs problems with class + variables

问题

下午好,我需要帮助解决我在tailwindcss + nextjs中遇到的一个大问题...

问题是关于设置类时,我需要使用一个变量,类在CSS中已设置,但tailwind没有将类转换为样式。

我需要它像这样:

Tailwindcss + Nextjs问题与类 + 变量

我已经尝试将类设置为常量,我尝试在组件内部和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:

Tailwindcss + Nextjs问题与类 + 变量

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}) =&gt; {
  const pokemonBgVariants = {
    pikachu: &#39;bg-pokemontype-pikachu&#39;,
    bulbasaur: &#39;bg-pokemontype-bulbasaur&#39;,
    // ...
  }

  return (
    &lt;div className=`[...other classes] ${pokemonBgVariants[pokemon.types[0].type.name]}`&gt;&lt;/div&gt;
  )
}

huangapple
  • 本文由 发表于 2023年2月19日 04:55:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75496338.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定