如何在Next.js中为按钮添加条件式className?
动态添加类名的实现方案
针对你的需求——当disabledIncrementButton为true时给按钮添加bg-vivense-gray-100类,这里有几种实用的实现方式:
1. 三元表达式 + 模板字符串(原生JSX写法)
直接在className里用三元表达式判断,把条件类和固定类拼接在一起,是最直接的原生实现方式:
<button className={`inline-flex items-center justify-center w-9 h-9 border-0 outline-0 bg-transparent cursor-pointer hover:bg-vivense-gray-100 transition ease-in-out duration-300 ${disabledIncrementButton ? 'bg-vivense-gray-100' : ''}`} disabled={disabledIncrementButton} onClick={increment} >
逻辑很直白:disabledIncrementButton为true时拼接目标类名,为false时拼接空字符串,完全不影响原有样式。
2. 数组过滤法(适配多条件场景)
如果之后需要添加更多条件类,用数组的方式会让代码结构更清晰:
<button className={[ 'inline-flex items-center justify-center w-9 h-9 border-0 outline-0 bg-transparent cursor-pointer hover:bg-vivense-gray-100 transition ease-in-out duration-300', disabledIncrementButton && 'bg-vivense-gray-100' ].filter(Boolean).join(' ')} disabled={disabledIncrementButton} onClick={increment} >
- 把固定类和条件类都放进数组,条件不满足时
disabledIncrementButton && 'xxx'会返回false - 用
filter(Boolean)过滤掉数组里的假值(false、空字符串等) - 最后用
join(' ')把数组转成空格分隔的类名字符串
3. 借助clsx/classnames库(简化写法)
如果你的项目已经安装了clsx或classnames这类工具库(不少React项目都会用到),写法会更简洁易读:
import clsx from 'clsx'; // ... <button className={clsx( 'inline-flex items-center justify-center w-9 h-9 border-0 outline-0 bg-transparent cursor-pointer hover:bg-vivense-gray-100 transition ease-in-out duration-300', { 'bg-vivense-gray-100': disabledIncrementButton } )} disabled={disabledIncrementButton} onClick={increment} >
clsx会自动处理条件判断,只将符合条件的类名合并进去,不用手动处理空值或拼接逻辑。
内容的提问来源于stack exchange,提问作者Nursena Karakulah
相关产品推荐
相关产品推荐

