React导航滚动定位报错:Cannot read properties of null (reading 'offsetTop')
问题修复方案
报错原因分析
你遇到的Cannot read properties of null (reading 'offsetTop')错误,核心有两个问题:
- Work和Contact的点击事件写法错误:直接把
scrollSection(work)、scrollSection(contact)写在onClick里,会导致组件渲染时立刻执行函数,此时对应ref还未挂载,current属性为null,自然无法读取offsetTop。 - 缺少Work和Contact的对应板块元素:从你贴的代码看,只有About板块绑定了
ref={about},Work和Contact的目标板块未在代码中出现,就算点击事件写法正确,ref也找不到对应的DOM元素。
修改后的完整代码示例
import React, { useRef } from 'react' // 记得导入video资源,原代码中使用了video变量但未导入 import video from './path/to/your/video.mp4' export default function Home() { const about = useRef(null); const work = useRef(null); const contact = useRef(null); const scrollSection = (elementRef) => { // 先做空值检查,避免ref未挂载时报错 if (!elementRef.current) return; window.scrollTo({ top: elementRef.current.offsetTop, behavior: "smooth", }); }; return ( <> {/* About板块 */} <div ref={about} className='first'> <nav className="navbar"> <div className="logo"> <video loop autoPlay muted playsInline className='logo_video' > <source src={video} type="video/mp4" /> </video> </div> <div className="about_section"> <ul className="list"> <li className="info about"> <div className="infoindex" onClick={() => scrollSection(about)}> About </div> </li> <li className="info"> {/* 改成箭头函数包裹,确保点击时才执行 */} <div className="infoindex" onClick={() => scrollSection(work)}> Work </div> </li> <li className="info"> {/* 同样用箭头函数包裹点击事件 */} <div className="infoindex" onClick={() => scrollSection(contact)}> Contact </div> </li> </ul> </div> </nav> </div> {/* 添加Work对应的板块,绑定work ref */} <div ref={work} className='work-section'> <h2>Work Section</h2> {/* 这里放置Work板块的具体内容 */} </div> {/* 添加Contact对应的板块,绑定contact ref */} <div ref={contact} className='contact-section'> <h2>Contact Section</h2> {/* 这里放置Contact板块的具体内容 */} </div> </> ) }
关键修改点
- 修正点击事件写法:将
onClick={scrollSection(work)}改为onClick={() => scrollSection(work)},确保只有点击时才触发滚动函数。 - 添加空值检查:在
scrollSection函数内先判断elementRef.current是否存在,避免组件初始化阶段调用函数导致报错。 - 补充目标板块元素:为Work和Contact各自添加对应的DOM元素并绑定ref,确保ref能找到滚动目标。
内容的提问来源于stack exchange,提问作者Ankit
相关产品推荐
相关产品推荐

