【问题标题】:How to write conditional css with changable values如何编写具有可变值的条件 css
【发布时间】:2023-01-30 19:30:52
【问题描述】:

我有一张看起来像这样的卡

    <Card.Header style={room.roomCapacity === room.students.length ? {backgroundColor: "#DC4C64"} : room.students.length === 0 ? {backgroundColor: '#14A44D'} : {backgroundColor: '#E4A11B'}} className={"text-center CardHeader"}>{room.roomNumber}</Card.Header>
    

但是我想在 css 中编写所有样式。那么如何在这些条件下将 style={} 函数实现到 css 中呢?

【问题讨论】:

    标签: javascript css reactjs frontend


    【解决方案1】:

    您可以使用 useMemo 的记忆功能来根据您的条件获得正确的颜色。

    import { useMemo } from 'react';
    
    const ExampleComponent = ({ room }) => {
      const isRoomFull = room.roomCapacity === room.students.length;
      const isRoomEmpty = room.students.length === 0;
    
      const backgroundColor = useMemo(() => {
        if (isRoomFull) {
          return '#DC4C64';
        }
    
        if (isRoomEmpty) {
          return '#14A44D';
        }
    
        return '#E4A11B';
      }, [isRoomFull, isRoomEmpty]);
    
      return (
        <Card.Header 
          className="text-center CardHeader"
          style={{
            backgroundColor
          }} 
        >
          {room.roomNumber}
        </Card.Header>
      );
    };
    

    【讨论】:

      猜你喜欢
      • 2016-11-27
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多