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

React中可在Tailwind类名内使用if/else判断实现动态样式切换吗?

问题原因与修复方案

你代码中存在三处错误导致背景色不生效:

  • React中指定元素类名需使用className属性,不能用原生HTML的class属性,class是JavaScript保留关键字,直接书写不会被React识别。
  • 三元表达式中的类名没有包裹引号,会被JSX解析为未定义的变量,无法正确生成类名字符串。
  • 逻辑判断写反:你需求是form为true时背景为白色,当前代码中form为true时返回的是黑色背景类名。

修正后的目标代码行

<div className={form ? 'bg-white' : 'bg-black'}>

优化后完整代码

import React, {useState} from 'react'
import axios from 'axios'
import ClientForm from './clientform.js'

function Clients() {
    const [name, setName] = useState('')
    const [weight, setWeight] = useState('')
    const [BMI, setBMI] = useState('')
    const [form, setForm] = useState(false)

    // 简化切换逻辑,不需要写if判断
    const toggleForm = () => setForm(prev => !prev)

    const submitForm = (e) => {
        e.preventDefault()
        const clients = {
            img: { data: Buffer, contentType: String },
            name: name,
            weight: weight,
            BMI: BMI
        }
        axios.post('/clients/add', clients)
        .then(res => console.log())
    }

    return (
        <div className={form ? 'bg-white' : 'bg-black'}>
            <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" onClick={toggleForm}>New Client</button>
            {form && <ClientForm />}
        </div>
    )
}

export default Clients

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 18:21:00