ReactDOM: 目标容器不是 DOM 元素

ReactDOM: Target container is not a DOM element

我正在使用 GatsbyJS 和 React 创建一个网站,我正在尝试对 DOM 进行更改。一开始我尝试用JS来做,研究后发现ReactDOM.

我在 JS 中尝试过,一开始它可以工作,然后它给了我一个错误:

(function() {

const today= new Date();
const hours = today.getHours();
const minute = today.getMinutes()
const element = document.getElementById('pintar');

if (hours >= 0 && hours < 9) {
   element.innerText = 'sleeping'
}else{
   element.innerText = 'Doing something else'
}
})()

我想做的是"write"在DOM一段文字中,根据一个条件(if语句),与当前时间相关。

当我第一次尝试一切正常时,但当我改变条件并满足时,出现以下错误:目标容器不是 DOM 元素

我从 React 开始,我无法对 DOM 进行更改。

我复制我的代码,看看我必须做什么才能在 DOM:

中进行这些更改
import React from "react"
import { Link } from "gatsby"
import ReactDOM from 'react-dom'

import Layout from '../components/layout'
import '../styles/index.scss'
import headerStyles from '../styles/header.module.scss'
import aboutStyles from '../styles/about.module.scss'
import { IoIosArrowRoundDown } from "react-icons/io";
import Clock from 'react-digital-clock';

const today= new Date();
const hours = today.getHours();
//const minute = today.getMinutes()
const pintar = document.getElementById('pintar');
const a = 'sleeping'
const b = 'Doing something else'

if (hours >= 0 && hours < 9) {
    ReactDOM.render(a, pintar)
}else{
    ReactDOM.render(b, pintar)
}

const About = () => {

    return(
        <Layout>
            <section className={headerStyles.header_wrapper}>
                <h3 className={headerStyles.header_wrapper_title}>About me</h3>
                <h1 className={headerStyles.header_wrapper_main}>Hey there
                </h1>
            </section>
            <IoIosArrowRoundDown className={headerStyles.header_arrow} />

            <p id='pintar'></p>

            <Clock className={aboutStyles.clock} hour12={false} format={'hh-mm'} />

        </Layout>
    )

}

export default About

通常,当使用 ReactDom.render 时,您将渲染反应结构之外的东西,但在您的情况下,您试图渲染反应结构内部的东西,您不应该这样做.

如果你想渲染里面的文字 <p id='pintar'></p> 你应该做的是

const About = () => {

    let pintar = ''

    // you can add any logic here and change pintar
    if (hours >= 0 && hours < 9) {
      pintar = 'something'
    } else {
      pintar = 'otherthing'
    }   

    return(
        <Layout>
            <section className={headerStyles.header_wrapper}>
                <h3 className={headerStyles.header_wrapper_title}>About me</h3>
                <h1 className={headerStyles.header_wrapper_main}>Hey there
                </h1>
            </section>
            <IoIosArrowRoundDown className={headerStyles.header_arrow} />

            // rendering pintar
            <p id='pintar'>{pintar}</p>

            <Clock className={aboutStyles.clock} hour12={false} format={'hh-mm'} />

        </Layout>
    )

}