You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+TypeScript中如何为scrollToSection函数的useRef参数指定类型?

React TypeScript中scrollToSection函数的Ref类型指定

你需要给scrollToSection的参数指定React.RefObject<HTMLElement>类型,这是useRef<HTMLElement>创建出来的Ref对象的标准类型。

修改后的完整代码如下:

import { useRef, RefObject } from 'react';

function Navbar() {
  const section1 = useRef<HTMLElement>(null);
  const section2 = useRef<HTMLElement>(null);
  const section3 = useRef<HTMLElement>(null);
  const section4 = useRef<HTMLElement>(null);

  const scrollToSection = (ref: RefObject<HTMLElement>) => {
    // 注意:API参数拼写应为behavior(美式拼写),原代码的behaviour会触发TypeScript报错
    ref.current?.scrollIntoView({ behavior: 'smooth' }); 
  };

  return (
    <nav>
      <NavLink to='/wiki'>Wiki</NavLink>
      {/* 示例调用: */}
      {/* <button onClick={() => scrollToSection(section1)}>跳转至区块1</button> */}
    </nav>
  );
}

额外补充两个关键点:

  • 如果你的目标区块是特定HTML元素(如div、section),可以将类型细化为HTMLDivElement或HTMLSectionElement,能获得更精准的类型提示
  • 必须确保从react中导入RefObject,或者直接使用完整类型标识React.RefObject<HTMLElement>

内容的提问来源于stack exchange,提问作者AnnoyingCuriosity

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.02 20:12:31