You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于React Props动态修改Tailwind类实现进度条宽度

动态Tailwind宽度类在Progress Bar组件中不生效

使用的依赖版本

"next": "13.4.4",
"react": "18.2.0",
"react-dom": "18.2.0",
"classnames": "^2.3.2",

问题描述

开发Progress Bar组件时,希望通过currentValue Prop动态设置Progress Thumb的Tailwind宽度类(如w-[10%]),但Chrome控制台显示类已存在的情况下,元素宽度并未生效。

组件代码如下:

import classNames from 'classnames'
import React from 'react'

type ProgressBarProps = {
  maxValue?: number
  currentValue: number
  showNumbers?: boolean
  orientation?: 'vertical' | 'horizontal'
}

export const ProgressBar = ({
  currentValue,
  maxValue = 100,
  showNumbers = true,
  orientation = 'vertical',
}: ProgressBarProps) => { 

  return (
    <div
      className={classNames('flex items-center w-full gap-2', {
        'flex-row': orientation === 'horizontal',
        'flex-col': orientation === 'vertical',
      })}
    >

      {/* Progress Wrapper */}
      <div className="flex items-center w-full h-2 gap-2 rounded-md bg-third-250">

       {/* Progress Thumb */}
        <div
          className={classNames(`h-full bg-primary-500 `, {
            'rounded-md': maxValue === currentValue,
            'rounded-tl-md rounded-bl-md': maxValue !== currentValue,
            [`w-[${currentValue}%]`]: currentValue,
          })}
        />

      </div>

      {/* 暂时无关的数值显示部分 */}
      {renderNumericProgress()}

    </div>
  )
}

已尝试以下写法,均无效果:

  • 直接拼接:className={w-[${currentValue}%]}
  • classNames包裹:className={classNames(w-[${currentValue}%])}}
  • twMerge处理:className={twMerge(w-[${currentValue}%])}}

解决方案

Tailwind CSS默认仅编译静态类名,动态拼接的类名(如w-[${currentValue}%])无法被构建时的扫描机制识别,因此不会生成对应的CSS规则。

方法1:用style属性直接设置宽度(推荐)

放弃动态Tailwind类,通过React的style属性直接计算并设置宽度,同时适配maxValue的比例:

<div
  className={classNames(`h-full bg-primary-500 `, {
    'rounded-md': maxValue === currentValue,
    'rounded-tl-md rounded-bl-md': maxValue !== currentValue,
  })}
  style={{ width: `${(currentValue / maxValue) * 100}%` }}
/>

方法2:让Tailwind识别动态类(不推荐)

若坚持使用Tailwind类,可在tailwind.config.js中通过safelist预生成所有可能的宽度类(会增加CSS打包体积):

// tailwind.config.js
module.exports = {
  content: [
    './app/**/*.{js,ts,jsx,tsx,mdx}',
    './components/**/*.{js,ts,jsx,tsx,mdx}',
  ],
  safelist: [
    // 预生成0-100%的宽度类
    ...Array.from({ length: 101 }, (_, i) => `w-[${i}%]`),
  ],
}

内容的提问来源于stack exchange,提问作者devpedrodias

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 08:10:09