Javascript 如何调用函数并根据React中的时间更改标题文本和颜色?

Javascript 如何调用函数并根据React中的时间更改标题文本和颜色?,javascript,html,css,reactjs,jsx,Javascript,Html,Css,Reactjs,Jsx,我正试图根据一天中的时间来更改h1标题中的文字和颜色。 我的代码出现错误:“无法将属性'innerText'设置为null” 我试图找出如何在渲染部分实现函数,但没有成功。 这是我的密码: 从“React”导入React; 从“react dom”导入react dom; const morning={color:“blue”}; const午后={color:“绿色”}; const night={color:“grey”}; const date=新日期(); const currentHo

我正试图根据一天中的时间来更改h1标题中的文字和颜色。
我的代码出现错误:“无法将属性'innerText'设置为null
我试图找出如何在渲染部分实现函数,但没有成功。
这是我的密码:

从“React”导入React;
从“react dom”导入react dom;
const morning={color:“blue”};
const午后={color:“绿色”};
const night={color:“grey”};
const date=新日期();
const currentHour=date.getHours();
函数sayHello(){
常量标题=document.querySelector(“h1”);
如果(当前小时<12){
heading.innerText=“早上好!”;
heading.style.color=早晨;
}否则如果(当前小时>12和当前小时<18){
heading.innerText=“下午好!”;
heading.style.color=下午;
}否则{
heading.innerText=“晚安!”;
heading.style.color=夜间;
}
}
ReactDOM.render(
{sayHello()},
document.getElementById(“根”)
);

我会使用
useState
useffect
挂钩

import React,{useState,useffect}来自“React”;
const morning={color:“blue”};
const午后={color:“绿色”};
const night={color:“grey”};
const SayHello=()=>{
const[helloText,setHelloText]=useState(“”);
const[helloTextColor,setHelloTextColor]=useState(“”);
useffect(()=>{
const date=新日期();
const currentHour=date.getHours();
如果(当前小时<12){
setHelloText(“早上好!”);
setHelloTextColor(上午);
}否则如果(当前小时>12和当前小时<18){
setHelloText(“下午好!”);
setHelloTextColor(下午);
}否则{
setHelloText(“晚安!”);
SETHELLOTEXTCLOR(夜间);
}
}, []);
返回{helloText};
};
导出默认的SayHello;

这不是您使用react的方式。您可能想尝试以下方法:

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

function Hello() {
  const currentHour = new Date().getHours();
  
  const [color, greeting] = 
    currentHour < 12 ? ["blue", "Good Morning!"] : 
    currentHour > 12 && currentHour < 18 ? ["green", "Good Afternoon!"] :
    ["grey", "Good Night!"];


  return (
    <h1 style={{color}}>
      {greeting}
    </h1>
  )
}

ReactDOM.render(
  <Hello />,
  document.getElementById("root")
);
从“React”导入React;
从“react dom”导入react dom;
函数Hello(){
const currentHour=新日期().getHours();
常量[颜色,问候语]=
当前时间<12?[“蓝色”,“早上好!”]:
当前时间>12和当前时间<18?[“绿色”,“下午好!”]:
[“格雷”,“晚安!”];
返回(
{问候语}
)
}
ReactDOM.render(
,
document.getElementById(“根”)
);

您还必须使用Set Time interval,它可以在1分钟后运行脚本,或者执行您想要设置的任何操作,然后您可以检查时间并更改状态。简单的在标题delcaration后写入
if(!heading)return null
当我包含该语句时,我会消除该错误,但结果是在我的h1中得到一个空字段。谢谢你帮我解决这个错误。试过了,但不知怎么的颜色还是没变。谢谢您的帮助。@Vukasin请再次检查。我帮你修好了所以最好的做法是使用?代替if和else语句,在render中将函数放在而不是{}中?这是个人的偏好,但根据我的经验,使用三元运算符通常会使代码更具声明性。
import React from "react";
import ReactDOM from "react-dom";

function Hello() {
  const currentHour = new Date().getHours();
  
  const [color, greeting] = 
    currentHour < 12 ? ["blue", "Good Morning!"] : 
    currentHour > 12 && currentHour < 18 ? ["green", "Good Afternoon!"] :
    ["grey", "Good Night!"];


  return (
    <h1 style={{color}}>
      {greeting}
    </h1>
  )
}

ReactDOM.render(
  <Hello />,
  document.getElementById("root")
);