0

時間に応じて h1 見出しのテキストと色の両方を変更しようとしています。
私のコードでは、「プロパティ 'innerText' を null に設定できません」というエラーが表示されます。
レンダリング部分に関数を実装する方法を見つけようとしましたが、成功しませんでした。
これが私のコードです:

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

const morning = { color: "blue" };
const afternoon = { color: "green" };
const night = { color: "grey" };
const date = new Date();
const currentHour = date.getHours();

function sayHello() {
  const heading = document.querySelector("h1");
  if (currentHour < 12) {
    heading.innerText = "Good Morning!";
    heading.style.color = morning;
  } else if (currentHour > 12 && currentHour < 18) {
    heading.innerText = "Good Afternoon!";
    heading.style.color = afternoon;
  } else {
    heading.innerText = "Good Night!";
    heading.style.color = night;
  }
}

ReactDOM.render(
  <h1 className="heading">{sayHello()}</h1>,
  document.getElementById("root")
);
4

3 に答える 3