如何使用 Typescript 在 React 中定义 <video> 引用的类型?
How can I define the type for a <video> reference in React using Typescript?
我正在尝试使用 React.js 中的 ref 来控制视频的 play/pause 状态,我的代码有效,但我正在尝试解决 tslint 错误:
function App() {
const playVideo = (event:any) => {
video.current.play()
}
const video = useRef(null)
return (
<div className="App">
<video ref={video1} loop src={bike}/>
</div>
);
}
这会导致
TS2531: Object is possibly 'null'.
所以我试着改变const video = useRef(null)
至 const video = useRef(new HTMLVideoElement())
我得到:
TypeError: Illegal constructor
我也试过:const video = useRef(HTMLVideoElement)
结果是:
TS2339: Property 'play' does not exist on type '{ new (): HTMLVideoElement; prototype: HTMLVideoElement; }'
要设置 ref 的类型,您可以像这样设置类型:useRef<HTMLVideoElement>()
。然后,为了处理对象可能是 null
的事实(因为在组件安装之前它是 null 或 undefined!),您可以只检查它是否存在。
const App = () => {
const video = useRef<HTMLVideoElement>();
const playVideo = (event: any) => {
video.current && video.current.play();
};
return (
<div className="App">
<video ref={video} loop src={bike} />
</div>
);
};
我正在尝试使用 React.js 中的 ref 来控制视频的 play/pause 状态,我的代码有效,但我正在尝试解决 tslint 错误:
function App() {
const playVideo = (event:any) => {
video.current.play()
}
const video = useRef(null)
return (
<div className="App">
<video ref={video1} loop src={bike}/>
</div>
);
}
这会导致
TS2531: Object is possibly 'null'.
所以我试着改变const video = useRef(null)
至 const video = useRef(new HTMLVideoElement())
我得到:
TypeError: Illegal constructor
我也试过:const video = useRef(HTMLVideoElement)
结果是:
TS2339: Property 'play' does not exist on type '{ new (): HTMLVideoElement; prototype: HTMLVideoElement; }'
要设置 ref 的类型,您可以像这样设置类型:useRef<HTMLVideoElement>()
。然后,为了处理对象可能是 null
的事实(因为在组件安装之前它是 null 或 undefined!),您可以只检查它是否存在。
const App = () => {
const video = useRef<HTMLVideoElement>();
const playVideo = (event: any) => {
video.current && video.current.play();
};
return (
<div className="App">
<video ref={video} loop src={bike} />
</div>
);
};