Jak*_*ers 4 html dom typescript reactjs use-ref
我正在尝试使用 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>
);
}
Run Code Online (Sandbox Code Playgroud)
这会导致
TS2531: Object is possibly 'null'.
Run Code Online (Sandbox Code Playgroud)
所以,我试图改变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; }'
Run Code Online (Sandbox Code Playgroud)
要为裁判的类型,你这样设置类型:useRef<HTMLVideoElement>()。然后,为了处理对象可能存在的事实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>
);
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1301 次 |
| 最近记录: |