React Functional Component:立即调用getElementById返回null

时间:2019-09-08 13:57:16

标签: reactjs

如果我添加一个0ms的超时,那么我可以控制台记录用document.getElementById选择的元素,但是如果我删除0ms的超时,它们都将返回null。这是怎么回事?

import React from 'react';

const Warning: React.FC = () => {

  setTimeout(() => {
    const confirm = document.getElementById("confirm");
    const invalid = document.getElementById("invalid");
    const confirmed = document.getElementById("confirmed");
    const warningBar = document.getElementById("warning-bar");
    console.log(confirm);
    console.log(invalid);
    console.log(confirmed);
    console.log(warningBar);
  },0);

  return (
    <div>
        <section className='warning-bar' id='warning-bar'>
            <div className='confirm' id='confirm'>Confirm</div>
            <div className='invalid' id='invalid'>Invalid</div>
            <div className='confirmed' id='confirmed'>Confirmed</div>
        </section>
    </div>
  );
}

export {Warning};

2 个答案:

答案 0 :(得分:0)

它是在加载组件之前执行的,因此您需要先渲染dom,然后再获取dom元素

答案 1 :(得分:0)

使用useEffect并提供一个空的依赖关系数组作为第二个参数,将在组件首次呈现后调用回调函数

import React, { useEffect } from 'react';

const Warning: React.FC = () => {
  useEffect(() => {
    const confirm = document.getElementById("confirm");
    const invalid = document.getElementById("invalid");
    const confirmed = document.getElementById("confirmed");
    const warningBar = document.getElementById("warning-bar");
    console.log(confirm);
    console.log(invalid);
    console.log(confirmed);
    console.log(warningBar);
  }, []);

  return (
    <div>
      <section className='warning-bar' id='warning-bar'>
        <div className='confirm' id='confirm'>Confirm</div>
        <div className='invalid' id='invalid'>Invalid</div>
        <div className='confirmed' id='confirmed'>Confirmed</div>
      </section>
    </div>
  );
};