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
相关产品推荐
相关产品推荐

