我在下面简化了这个问题,我使用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>
);
};```
答案 0 :(得分:1)
您不能在块外部访问变量。如果要访问,则需要在useEffect块之外声明所有变量。您可以通过以下多种方式进行操作。
方法1:在外部声明变量。
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>
);
};