【问题标题】:How to define time ranges in React?如何在 React 中定义时间范围?
【发布时间】:2021-08-22 04:24:47
【问题描述】:

这是我的代码。我试图定义一个小时范围,以便它根据一天中的时刻改变颜色,但我不知道如何创建一个范围(例如从 7 点到 12 点 -> 早上)。现在的问题是,如果我把凌晨 3 点设置为早上,我想让它说晚上,但是,当然,我不能超过 23 小时来设置晚上。你能帮帮我吗?

import React from "react";
import ReactDOM from "react-dom";

const date = new Date(2021, 1, 1, 3);

const time = date.getHours();

let customStyle = {
  color: ""
};

function getTime() {
  const morning = time < 12;
  const afternoon = time < 18;
  const night = time < 23;

  if (morning) {
    customStyle = {
      color: "red"
    };
    return "Good morning";
  } else if (afternoon) {
    customStyle = {
      color: "green"
    };
    return "Good afternoon";
  } else if (night) {
    customStyle = {
      color: "blue"
    };
    return "Good night";
  }
}

console.log(getTime());

ReactDOM.render(
  <h1 className="heading" style={customStyle}>
    {" "}
    {getTime()}{" "}
  </h1>,

  document.getElementById("root")
);

【问题讨论】:

    标签: javascript reactjs time


    【解决方案1】:

    您需要根据位置和日期获取日出时间。您可以为此使用 sunrise-sunset-js 库。

    【讨论】:

      【解决方案2】:

      你可以更精确地定义你的范围

      const morning = false;
      const afternoon = false;
      const night = false;
      
      if (time > 7 && time <= 12) {
      morning = true;
      } else if (time > 12 && time <= 18) {
      afternoon = true;
      } else {
      night = true;
      }
      

      【讨论】:

      • 这成功了!非常感谢潘。我也尝试了这条路,但我遇到的问题是我在 && 之前和之后没有“时间”,所以就像-> if (time > 7 && 12 &&
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多