将 CSS 类动态添加到 React 中的元素
Dynamically add CSS classes to Elements in React
使用模板字面量将 CSS 类动态添加到 React 元素。模板文字用反引号分隔,并允许我们使用美元符号和花括号${expression}
语法嵌入变量和表达式。
应用程序.js
import {useState} from 'react'; import './App.css'; export default function App() { const [isActive, setIsActive] = useState(false); const handleClick = event => { // 👇️ toggle isActive state variable setIsActive(current => !current); }; const myClass = 'bg-salmon'; return ( <div> <div className={`text-white ${myClass}`}>Hello world</div> <br /> <button className={`font-lg ${isActive ? 'bg-salmon text-white' : ''}`} onClick={handleClick} > Click </button> </div> ); }
这是示例的 CSS。
应用程序.css
.bg-salmon { background-color: salmon; } .text-white { color: white; } .font-lg { font-size: 2rem; padding: 10px 10px; }
我们可以在设置类时使用
模板文字
来连接字符串和变量。
请注意,字符串包含在反引号 “ 中,而不是单引号中。
美元符号和花括号语法允许我们使用被评估的占位符。
应用程序.js
<div className={`text-white ${myClass}`}> Hello world </div> <button className={`font-lg ${isActive ? 'bg-salmon text-white' : ''}`} onClick={handleClick} > Click </button> <div className={`text-white ${'hi'.length === 2 ? 'bg-salmon' : ''}`}> Hello world </div>
The curly braces we wrapped the template literal in mark the beginning of an
expression that has to be evaluated.
The code between the opening an closing curly brace is just JavaScript, so any variable or expression we use in our template literals will get evaluated.
The second example in the code snippet uses the
ternary operator.
App.js
<button className={`font-lg ${isActive ? 'bg-salmon text-white' : ''}`} onClick={handleClick} > Click </button>
The ternary operator is basically an if/else
statement.
The part before the question mark gets evaluated and if it returns a truthy value, the operator returns the value before the colon, otherwise it returns the value after the colon.
In other words, if the isActive
variable stores a true
value, we add the
bg-salmon
and text-white
classes to the element, otherwise we return an
empty string.