2024年04月01日 建站教程
react运用ref报错返回undefined或null是什么原因,下面web建站小编给大家介绍一下解决方法!
原因分析:导致报错的原因是在触发之前就执行了ref。
正确写法:
import {useRef, useEffect} from 'react';
export default function App() {
const ref = useRef();
console.log(ref.current); // ?️ undefined here
useEffect(() => {
const el2 = ref.current;
console.log(el2); // ?️ element here
}, []);
const handleClick = () => {
console.log(ref.current); // ?️ element here
};
return (
<div>
<div ref={ref}>
<h2>Hello</h2>
</div>
<button onClick={handleClick}>Click</button>
</div>
);
}
本文链接:http://so.lmcjl.com/news/856/