簡體   English   中英

如何通過 Tailwind 和 React 有條件地應用類名 (JIT)? [解決]

[英]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中被選中,它也不起作用我錯過了什么嗎?

我知道發生了什么。 我傳遞的是實際值而不是密鑰。

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>
  );
};

您可以使用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
    })

供您參考: https://www.npmjs.com/package/clsx

您可以為此使用三元條件檢查。

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM