[英]React conditionally apply color to component
我正在嘗試根據 4 個條件有條件地將顏色應用於 div。 我通常在 className 屬性中使用三元運算符,但有 4 個條件,必須有更好的方法來做到這一點。
例如,
<div className={`${styles.card} ${items.length > 1 && styles.blue} ${items.length > 2 && styles.green}` etc...}>data</div>
我不能使用任何其他庫,要么它必須使用 react
您可以有條件地使用類構建一個數組:
const Card = () => {
const classNames = [styles.card];
if (items.length === 1) {
classNames.push(styles.blue);
} else if (items.length > 1) {
classNames.push(styles.green);
}
return (
<div className={classNames.join(' ')}>data</div>
)
};
編輯:修改條件以使其更有意義。
我會使用classcat
package。 對我來說,是根據不同條件組合多個 class 名稱的最佳方法。
import cc from "classcat";
<div
className={cc([
{
[styles.card]: true,
[styles.blue]: items.length > 1,
[styles.green]: items.length > 2,
},
])}
>
data
</div>
也許是返回 styles 的方法
const Card = () => {
const handleStyles = () => {
const classNames = [styles.card];
if (items.length === 1) {
classNames.push(styles.blue);
}
else if (items.length > 1) {
classNames.push(styles.green);
}
return classNames.join('');
}
return (
<div className={handleStyles}>data</div>
)
};
您還可以為您的項目添加classnames
名 package。 使用它很常見。
<div
className={
classNames('styles.card', {
styles.blue: items.length > 1,
styles.green: items.length > 2,
})
}
>data</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.