你能把一个if/else语句在一个顺风类在反应?



我试图改变一个div的背景色,如果它是真的,div的背景色应该是白色,否则,它的背景色应该是黑色。

我试过用if/else语句来做,但它似乎不起作用,因为它总是呈现黑色背景。

这是我要修改的行:

<div class="{form ? bg-black : bg-white}">

这是我的代码:

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)
const toggleForm = () => {
if(form === false) {
setForm(true)
} else {
setForm(false)
}
}
const submitForm = (e) => {
e.preventDefault()
const clients = {
img: 
{ data: Buffer, contentType: String },
name: name, //reference to the associated book
weight: weight,
BMI: BMI
}
axios.post('/clients/add', clients)
.then(res => console.log())
}
return (
<div class="{form ? bg-black : bg-white}">
<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" onClick={toggleForm}>New Client</button>
{form ? <ClientForm /> : void(0)}
</div>
)
}
export default Clients

这将类设置为一个看起来像表达式的大字符串字面值:

class="{form ? bg-black : bg-white}"

您希望使用表达式并将其解析为字符串字面值:

class={form ? "bg-black" : "bg-white"}

作为题外话,我可能是错误的,但我认为,在React JSX的class属性需要是className:

className={form ? "bg-black" : "bg-white"}

你可以做<div class="{form ? 'bg-black : 'bg-white'}">吗?

正确的代码是:

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

相关内容

最新更新