web建站教程
  1. 首页
  2. vuejs
  3. js
  4. 好玩
  5. seo教程
  6. 前端知识
  7. 百度echarts
  8. 更多
    php入门
    nodejs
    mockjs
    reactjs
    mysql
    wordpress
    织梦cms
    帝国cms
    git教程
    IT知识
    模板大全
    休息站

react运用ref报错返回undefined或null怎么解决

1434 ℃
     

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>
  );
}

javascript如何判断是否存在

el-dialog中获取el-table组件的ref值报undefined错误!

vuejs点击重置报"TypeError: Cannot read properties of undefined (reading 'resetFields')"错误

标签: ref报错, undefined

上面是“react运用ref报错返回undefined或null怎么解决”的全面内容,想了解更多关于 reactjs 内容,请继续关注web建站教程。

当前网址:https://ipkd.cn/webs_3275.html

声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!

当前位置: 网站首页 > reactjs
本文共计445个字,预计阅读时长3分钟
生活小工具,收录了80多款小工具
上一篇: 推荐一款免费可商用仿宋字体——汉字之美仿宋GBK
下一篇: 推荐一款免费可商用英文字体——Atkinson Hyperlegible
x 打工人ai神器