gpt4 book ai didi

reactjs - react 功能组件 : How to access variables from outside useEffect()

转载 作者:行者123 更新时间:2023-12-03 21:18:21 27 4
gpt4 key购买 nike

我已经简化了下面的问题,我正在使用 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>
);
};```

最佳答案

您不能访问块外的变量。如果要访问,则需要在 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>
);
};

Demo Link

关于reactjs - react 功能组件 : How to access variables from outside useEffect(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57842928/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com