在React中如何使用Typescript定义<video>引用的类型?

10
我正在尝试使用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' Kamermans
1
@Mike'Pomax'Kamermans useRefcreateRef 的 Hook 版本。 - cbr
ref={video1} 应该改为 ref={video}。 - Dev Null
1个回答

15

要为引用设置类型,可以像这样设置类型: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>
  );
};

我在 Twilio 的示例 React 应用程序中看到了 useRef<HTMLVideoElement>(null!) 这个语法,但是我无法理解这个语法。我以前从未见过这种语法,并且在 React 文档中也找不到它。你有更多关于它的信息来源吗?谢谢。 - Panpaper
2
@Panpaper useRef 是 React 的一个钩子。useRef(null) 用 null 初始化其值。useRef<HTMLVideoElement>(null) 是 TypeScript,告诉编译器 ref 中存储的值是 HTMLVideoElement 类型。<>泛型 相关。感叹号称为 非空断言操作符 - cbr
1
@Panpaper 不确定那里是否需要感叹号。这可能取决于您的TypeScript版本和tsconfig设置。 - cbr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接