React Functional Component:如何从 useEffect() 外部访问变量

IT技术 reactjs
2021-04-28 00:59:59

我已经简化了下面的问题,我使用useEffect来确保在选择项目之前渲染了 dom,这很好用并且在尝试获取这些元素之前不需要超时,但是如果我想在中使用这些值另一个组件我如何访问它们?

printAll()函数无法找到变量。

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");
  }, []);

  function printAll () {
    console.log(confirm);
    console.log(invalid);
    console.log(confirmed);
    console.log(warningBar);
  }

printAll()

  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>
  );
};```
1个回答

您不能访问块外的变量。如果要访问,则需要在 useEffect 块之外声明所有变量。您可以通过多种方式进行操作,如下所示。

方法一:在外面声明变量。

import React, { useEffect } from 'react';

const Warning: React.FC = () => {
  let confirm;
  let invalid;
  let confirmed;
  let warningBar;

  useEffect(() => {
    confirm = document.getElementById("confirm");
    invalid = document.getElementById("invalid");
    confirmed = document.getElementById("confirmed");
    warningBar = document.getElementById("warning-bar");
    printAll();
  }, []);

  function printAll () {
    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>
  );
};

方法 2:使用 useRef

import React, { useEffect, useRef } from 'react';

const Warning: React.FC = () => {
  let confirm = useRef({});
  let invalid = useRef({});
  let confirmed = useRef({});
  let warningBar = useRef({});

  useEffect(() => {
    printAll()
  }, []);

  function printAll () {
    console.log(confirm.current);
    console.log(invalid.current);
    console.log(confirmed.current);
    console.log(warningBar.current);
  }

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

演示链接