【问题标题】:tailwindcss dynamic border-color using template string doesn't work使用模板字符串的 tailwindcss 动态边框颜色不起作用
【发布时间】:2023-01-02 02:40:02
【问题描述】:

我正在使用 react 18、nextjs 13 和 tailwindcss、postcss、autoprefixer

期望:单击按钮切换边框颜色和其他样式 行为:除边框颜色外的所有样式切换

问题:为什么 border-color 的行为方式与其他样式不同?

损坏的代码:

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>
    </>
  )
}

【问题讨论】:

    标签: javascript css reactjs tailwind-css


    【解决方案1】:

    解决方案:根据 tailwindcss 文档

    不要动态构造类名

    始终使用完整的类名

    https://tailwindcss.com/docs/content-configuration#dynamic-class-names

    工作代码:

    // ...
      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'
    // ...
    

    不同之处在于,整个实用程序类是有条件地构造的,然后插入到 jsx className 属性中的模板字符串文字中。

    问题:我仍然想知道为什么这个 border-color 案例不同,因为我在有条件地构建实用程序类时遇到过一些这样的案例。

    【讨论】:

      猜你喜欢
      • 2023-02-05
      • 2020-11-25
      • 2017-04-04
      • 2021-12-31
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 2021-05-18
      • 2021-08-16
      相关资源
      最近更新 更多