[英]How to conditionally apply classNames (JIT) with Tailwind and React? [Resolved]
我有以下 object map:
const stylesMap = {
level: {
1: "text-5xl",
...
},
};
在我的組件中,我有:
const ComponentExample = (props) => {
const { level } = props;
return (
<h1 className={classNames(stylesMap.level[level ?? stylesMap.level[1]])}>
Test
</h1>
);
};
作為一個測試,我做了一個level: null
期望值"text-5xl"
成為類名列表的一部分,但我沒有看到它。 如果道具是 null,我只是想設置默認值。
我什至在 tailwindcss 配置中添加了safelist: ["text-5xl"]
,但即使它已經在stylesMap
中被選中,它也不起作用我錯過了什么嗎?
我知道發生了什么。 我傳遞的是實際值而不是密鑰。
const ComponentExample = (props) => {
const { level } = props;
return (
<h1 className={classNames(stylesMap.level[level ?? 1])}>
Test
</h1>
);
};
您可以使用clsx
庫。 它用於有條件地應用類名。
<h1 className={clsx({[stylesMap.level[1]: level]})}>
Test
</h1>
前任:
const menuStyle = clsx({
[classes.root] : true, //always applies
[classes.menuOpen] : open //only when open === true
})
您可以為此使用三元條件檢查。
const ComponentExample = (props) => { const { level } = props; return ( <h1 className={level === null? "text-5xl": null}> Test </h1> ); };
你可以這樣試試
const ComponentExample = (props) => {
const { level } = props;
return (
<h1
className={
stylesMap?.level && stylesMap?.level[1]
? stylesMap.level[1]
: 'text-5xl'
}
>
Test
</h1>
);
};
Condition = 檢查以決定給出哪個 className 的條件
trueValue = 條件為真時給出的類名
falseValue = 條件為假時給出的類名
<h1 className={condition ? trueValue : falseValue}>
Test
</h1>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.