在 React 中使用 CLSX 有條件地應用類

本文將解釋 clsx()
函式並有條件地在 React 中應用類。
React 中的 clsx()
函式
同名包中的 clsx()
函式是一個 JavaScript 實用程式,用於設定設定 className
屬性值的條件。它接受無限數量的引數,不限於一種特定型別。
最終,clsx()
函式返回一個 string
插值,檢查 JavaScript 變數的 boolean
值並相應地應用類。
當然可以自己編寫這些字串,但它比簡單地使用 clsx()
函式要耗時得多。
檢視官方 npm 文件。
在 React 中使用 clsx()
函式設定條件類
React 開發人員使用 clsx()
函式來應用類。
我們可以設定應用特定類需要滿足的條件,但這不是必需的。
例子:
import "./styles.css";
import clsx from "clsx";
const classNameOne = "redButton";
const classNameTwo = "blueBorder";
export default function App() {
const number = 3;
return (
<div className="App">
<button className={clsx(classNameOne, { [classNameTwo]: number > 5 })}>
A sample button
</button>
</div>
);
}
在上面的示例中,我們有兩個具有字串型別值的變數。我們還有一個變數,稱為 number
,設定為任意數字,以演示 clsx()
函式如何有條件地應用於(或不應用於)指定的類。
classNameOne
函式的第一個引數沒有任何關聯的條件,因此無論如何它通常都會被應用。第二個引數是具有 classNameTwo
屬性的 key-value
對和條件作為其值的物件。
在這種情況下,number
變數的值為 3,不超過 5,因此 classNameTwo
不適用。嘗試更改 CodeSandbox 上的值,看看自己會發生什麼。
這是基本條件樣式的示例。乍一看,你並不明白為什麼需要 clsx()
函式,但是一旦你的樣式設定條件變得更加複雜,clsx()
允許你輕鬆設定這些條件。
Irakli is a writer who loves computers and helping people solve their technical problems. He lives in Georgia and enjoys spending time with animals.
LinkedIn