改变内联 css 与反应问题

Alter inline css with react issue

我正在映射我的 Gatsby 前端中的一些日期值,我正在从我的 Strapi 后端检索这些值。

我想要实现的是根据 {item.end} 的值是否大于当前日期来更改背景颜色。 {item.end} 包含日期值。

我做了一个普通的 if-else 语句来检查这种情况,当控制台记录时,它会根据日期值返回正确的循环迭代次数和正确的响应。

但是当我尝试对我的道具应用相同的逻辑时:

<h4 className={
    TodayDate.getDate() > courseEndDate? "educationsOver": "job-desc"
}>{item.title}
</h4>

classes 不是动态应用的。未应用任何更改,仅应用 .job-desc 的标准 class。

这是我当前的代码:

{course.map(item => {

            let courseEndDate = item.end
            //console.log(`Course end date: ${courseEndDate}`)
            const TodayDate = new Date()
            courseEndDate = new Date(courseEndDate)

            if (TodayDate > courseEndDate) {
              console.log(
                `${courseEndDate} Course end date is not greater than the current date ${TodayDate}.`
              )
            } else {
              console.log(
                `${courseEndDate} Course end date is greater than the current date ${TodayDate}.`
              )
            }

            return (
              <div key={item.id} className="job-desc">
                <h4>Kurs:</h4>
                <h4
                  className={
                    TodayDate.getDate() > courseEndDate
                      ? "educationsOver"
                      : "job-desc"
                  }
                >
                  {item.title}
                </h4>
                <span>{item.credits}&nbsp;poäng</span>
                <span>startdatum: {item.start}</span>&nbsp;
                <span>slutdatum: {item.end}</span>
              </div>
            )
          })}

我的代码中缺少什么?

我认为您的代码应该如下所示:

<h4 className={TodayDate > courseEndDate ? "educationsOver" : "job-desc"}>

注意删除 getDate()

How would I change the code, based upon the same date conditions if I just want to change the background on job-desc

就这样:

        return (
          {TodayDate.getDate() > courseEndDate 
          ? 
          <div key={item.id} className="classname-1">
            <h4>Kurs:</h4>
            <h4 className="educationsOver">
              {item.title}
            </h4>
            <span>{item.credits}&nbsp;poäng</span>
            <span>startdatum: {item.start}</span>&nbsp;
            <span>slutdatum: {item.end}</span>
          </div>
          : <div key={item.id} className="classname-2">
            <h4>Kurs:</h4>
            <h4 className="job-desc">
              {item.title}
            </h4>
            <span>{item.credits}&nbsp;poäng</span>
            <span>startdatum: {item.start}</span>&nbsp;
            <span>slutdatum: {item.end}</span>
          </div>
         }
        )

最终使用与以下所述相同的方法修复:

<h4 style={{ color: TodayDate > courseEndDate ? "red" : "grey",}} > {item.title} </h4>