简体   繁体   English

如何通过 Tailwind 和 React 有条件地应用类名 (JIT)? [解决]

[英]How to conditionally apply classNames (JIT) with Tailwind and React? [Resolved]

I have the following object map:我有以下 object map:

const stylesMap = {
  level: {
    1: "text-5xl",
    ...
  },
};

In my component I have:在我的组件中,我有:

const ComponentExample = (props) => {
  const { level } = props;
  return (
    <h1 className={classNames(stylesMap.level[level ?? stylesMap.level[1]])}>
      Test
    </h1>
  );
};

As a test I have made level: null expecting the values "text-5xl" to be part of the classNames list but I don't see it.作为一个测试,我做了一个level: null期望值"text-5xl"成为类名列表的一部分,但我没有看到它。 I'm simply trying to set default values if the props are null.如果道具是 null,我只是想设置默认值。

I even add safelist: ["text-5xl"] in the tailwindcss config but that didn't work even though its already picked up in stylesMap Am I missing anything?我什至在 tailwindcss 配置中添加了safelist: ["text-5xl"] ,但即使它已经在stylesMap中被选中,它也不起作用我错过了什么吗?

I know what happened.我知道发生了什么。 I was passing the actual value instead of the key.我传递的是实际值而不是密钥。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

const ComponentExample = (props) => {
  const { level } = props;
  return (
    <h1 className={classNames(stylesMap.level[level ?? 1])}>
      Test
    </h1>
  );
};

you can use clsx library.您可以使用clsx库。 It's used for applying classNames conditionally.它用于有条件地应用类名。

<h1 className={clsx({[stylesMap.level[1]: level]})}>
   Test
</h1>

Ex:前任:

const menuStyle = clsx({
        [classes.root] : true, //always applies
        [classes.menuOpen] : open //only when open === true
    })

For your reference: https://www.npmjs.com/package/clsx供您参考: https://www.npmjs.com/package/clsx

You could use ternary condition check for this.您可以为此使用三元条件检查。

 const ComponentExample = (props) => { const { level } = props; return ( <h1 className={level === null? "text-5xl": null}> Test </h1> ); };

You can try it this way你可以这样试试

const ComponentExample = (props) => {
  const { level } = props;
  return (
    <h1
      className={
        stylesMap?.level && stylesMap?.level[1]
          ? stylesMap.level[1]
          : 'text-5xl'
      }
    >
      Test
    </h1>
  );
};

Condition = condition to check for deciding which className to give Condition = 检查以决定给出哪个 className 的条件

trueValue = the className to give in case the condition is true trueValue = 条件为真时给出的类名

falseValue = the className to give in case the condition is false falseValue = 条件为假时给出的类名

<h1 className={condition ? trueValue : falseValue}>
     Test
</h1>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM