简体   繁体   English

反应中的条件运算符不适用于 css

[英]conditional operator in react not working with css

In my task component on the parent div I am trying to make it so when reminder is set to true it adds a "reminder" class to the div, which just adds a border left.在父 div 上的任务组件中,我试图做到这一点,因此当提醒设置为 true 时,它会在 div 中添加一个“提醒”class,它只会在左侧添加一个边框。 If reminder is set to false the "reminder" class will not be added.如果提醒设置为 false,则不会添加“提醒”class。

I have checked and on double click the reminder does toggle between true and false so I know that works.我已经检查并双击提醒确实在真假之间切换,所以我知道这是有效的。


const Task = ({ task, onDelete, onToggle }) => {
    return (
        <div
            className={`task ${task.reminder ?
                'reminder' : ''}`}
            onDoubleClick={() => onToggle(task.id)} className="task">
            <h3>{task.text} <FaTimes
                onClick={() => onDelete(task.id)}
                style={{
                    color: "red", cursor: "pointer"
                }} />
            </h3>

            <p>{task.day}</p>
        </div>
    )
}

export default Task

.task {
  background: #f4f4f4;
  margin: 5px;
  padding: 10px 20px;
  cursor: pointer;
  
}

.task.reminder {
  border-left: 5px solid green !important; 
}

onToggle, you are not passing task.remainder, how will task.remainder changes? onToggle,你不是传task.remainder,task.remainder会怎么变化? Please pass task.remainder in onToggle function Your code must look like this.请在 onToggle function 中传递 task.remainder 您的代码必须如下所示。

<div className={ task ${task.reminder?'reminder': ''} } onDoubleClick={() => onToggle(task.remainder)} className="task"> <div className={ task ${task.reminder?'reminder': ''} } onDoubleClick={() => onToggle(task.remainder)} className="task">

I think you are adding className 2 times in div element remove 2nd one then you will get your result.我认为您在 div 元素中添加了 2 次 className ,删除了第 2 次,然后您将得到结果。 Actually, your logic is correct but you did that small mistake adding className 2 times.实际上,您的逻辑是正确的,但是您在添加 className 2 次时犯了那个小错误。

Btw, there is 2 ways to implement that logic-顺便说一句,有两种方法可以实现该逻辑-

className={`${task.reminder? 'task reminder': 'task'}`}

className={`task ${task.reminder? 'reminder': ''}`}

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

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