我正在尝试使用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: Illegal constructor
我也尝试过:const video = useRef(HTMLVideoElement)
结果是:
TS2339: Property 'play' does not exist on type '{ new (): HTMLVideoElement; prototype: HTMLVideoElement; }'
要设置引用的类型,您可以设置以下类型:useRef<HTMLVideoElement>()
。然后,要处理对象可能存在的事实null
(因为在装入组件之前它为null或未定义!),您只需检查它是否存在。
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>
);
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句