简体   繁体   English

React 有条件地向组件应用颜色

[英]React conditionally apply color to component

I am trying to apply a color to a div conditionally based on 4 conditions.我正在尝试根据 4 个条件有条件地将颜色应用于 div。 I usually use the ternary operator in the className prop but there is 4 conditions and there has got to be a better way to do this.我通常在 className 属性中使用三元运算符,但有 4 个条件,必须有更好的方法来做到这一点。

For example,例如,

<div className={`${styles.card} ${items.length > 1 && styles.blue} ${items.length > 2 && styles.green}` etc...}>data</div>

I cant use any other libraries either its just got to be using react我不能使用任何其他库,要么它必须使用 react

You could build an array up with classes conditionally:您可以有条件地使用类构建一个数组:

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

Edit: Modified conditions to make more sense.编辑:修改条件以使其更有意义。

I would use classcat package.我会使用classcat package。 For me is the best approach to combine multiple class names based on different conditions.对我来说,是根据不同条件组合多个 class 名称的最佳方法。

import cc from "classcat";

<div
     className={cc([
       {
         [styles.card]: true,
         [styles.blue]: items.length > 1,
         [styles.green]: items.length > 2,
       },
     ])}
>
   data
</div>

Maybe a method that return the styles也许是返回 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>
  )
};

You can also add classnames package for your project.您还可以为您的项目添加classnames名 package。 It's very common to use it.使用它很常见。

<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.

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