我正在尝试使用React.js中的ref控制视频的播放/暂停状态,我的代码可以运行,但是有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: 不合法的构造函数
我也尝试过:const video = useRef(HTMLVideoElement)
结果是:
TS2339: Property 'play' does not exist on type '{ new (): HTMLVideoElement; prototype: HTMLVideoElement; }'
<video>
元素。不要使用src
属性,而是使用<source>元素。此外,如果这是实际的React,请使用createRef来创建引用。 - Mike 'Pomax' KamermansuseRef
是createRef
的 Hook 版本。 - cbr