Typescript中点击事件传入DOM元素作为函数入参应使用什么类型?
你可以把pressedElement参数的any类型直接替换为Element,这个类型完全适配你的使用场景:
- 你场景中用到的
<svg>元素和所有HTML元素都继承自Element接口,兼容性足够 Element接口自带你代码中用到的ownerDocument属性,不会触发TypeScript类型报错
如果想要更严谨,贴合TypeScript原生的事件对象类型定义,可以补充类型守卫处理边界情况:
const handleClick = (pressedElement: EventTarget | null) => { // 非Element类型的target直接终止逻辑,避免报错 if (!(pressedElement instanceof Element)) return; const anchor = (pressedElement.ownerDocument || document).querySelector('#back-to-top-anchor'); if (anchor) { anchor.scrollIntoView({ behavior: 'smooth', block: 'center' }); } };
顺便你代码里组件props的any类型也可以同步优化,完整优化后代码如下:
import useScrollTrigger from '@material-ui/core/useScrollTrigger'; import Zoom from '@material-ui/core/Zoom'; import { PropsWithChildren } from 'react'; import './Catalog.scss'; const ScrollTop = (props: PropsWithChildren<{ window?: () => Window }>) => { const { children, window } = props; const trigger = useScrollTrigger({ target: window ? window() : undefined, disableHysteresis: true, threshold: 100, }); const handleClick = (pressedElement: Element) => { const anchor = (pressedElement.ownerDocument || document).querySelector('#back-to-top-anchor'); if (anchor) { anchor.scrollIntoView({ behavior: 'smooth', block: 'center' }); } }; return ( <Zoom in={trigger}> <div onClick={({ target }) => handleClick(target as Element)} role="presentation" className="scrollTop" > {children} </div> </Zoom> ); } export default ScrollTop;
上面代码里给target加了as Element类型断言,因为TypeScript原生定义的点击事件target类型为EventTarget | null,而我们确定此处触发点击的一定是DOM元素,所以直接断言即可。
内容的提问来源于stack exchange,提问作者rumon
相关产品推荐
相关产品推荐

