[英]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.