【问题标题】:Multiple CSS conditional classes using React使用 React 的多个 CSS 条件类
【发布时间】:2018-10-31 21:29:25
【问题描述】:

我想将 3 个更多条件类合并到这个...

<li className={`list-group-item ${todo.completed ? " strike-through" : ""}`}

我现在希望 ${todo.priority} 被包含/与之一起,它将分配类:

"警报警报信息", “警报警报警告”, 和 “警报警报-危险” 基于下拉列表中的相应值:1、2、3。

谁能帮我解决这个问题,提前谢谢!

【问题讨论】:

  • todo.priority 会与 todo.completed 并排,还是两者之一?
  • 另外,谢谢。

标签: css reactjs


【解决方案1】:

其他人已经提供了一些更“灵活”的解决方案,所以我将添加快速和肮脏的解决方案:

<li className={`list-group-item ${todo.completed ? " strike-through" : ""} ${todo.priority === 1 ? "alert alert-info" : (todo.priority === 2 ? "alert alert-warning" : "alert alert-danger")}`} />

为了便于阅读:

const completed = todo.completed ? " strike-through" : "";
const priority = todo.priority === 1 ? "alert alert-info" : (todo.priority === 2 ? "alert alert-warning" : "alert alert-danger");
...
<li className={`list-group-item ${completed} ${priority}`} />

【讨论】:

    【解决方案2】:

    我推荐classnames 包。它是一个广泛使用的包,目的很简单。任何值为真值的键都会成为最终的类名:

    import cx from 'classnames';
    
    <li className={cx('list-group-item', {
       'alert alert-danger': value === 3,
       'alert alert-info': value === 1,
       'alert alert-warning': value === 2,
       'strike-through': todo.completed,
    })} />
    

    【讨论】:

      【解决方案3】:

      您可以继续以同样的方式添加类,或者您可以使用像 classnames 这样的库来简化编写类的过程。

      示例

      import React from 'react';
      import classNames from 'classnames';
      
      class App extends React.Component {
        // ...
      
        render() {
          // ...
      
          const className = classNames({
            'list-group-item': true,
            'strike-through': todo.completed,
            'alert alert-info': todo.priority === 1,
            'alert alert-warning': todo.priority === 2,
            'alert alert-danger': todo.priority === 3,
          });
          return <li className={className}> ... </li>;
        }
      }
      

      【讨论】:

        【解决方案4】:

        我想这就是你要找的东西:

        import clsx from "clsx";
        
        className={
          clsx(classes.firstClass,  
          { [classes.coach]: user.id === "F6E2080B-E61F-416D-8841-3E0249DF2715" })
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-11-23
          • 2020-03-08
          • 2017-01-09
          • 1970-01-01
          • 2018-03-31
          • 1970-01-01
          • 2022-11-16
          • 1970-01-01
          相关资源
          最近更新 更多