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

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)

cub*_*brr 5

要为裁判的类型,你这样设置类型: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)

  • 我在 Twilio 的示例 React 应用程序中看到了这个 `useRef&lt;HTMLVideoElement&gt;(null!)` 语法,但无法弄清楚这个语法。我以前从未见过这个,并且在 React 文档中找不到它。您有更多相关信息的来源吗?谢谢 (2认同)
  • @Panpaper [`useRef`](https://reactjs.org/docs/hooks-reference.html#useref) 是一个 React 钩子。`useRef(null)` 用 null 初始化它的值。`useRef&lt;HTMLVideoElement&gt;(null)` 是 TypeScript,它告诉编译器存储在 ref 中的值是 `HTMLVideoElement` 类型。`&lt;&gt;` 与 [generics](https://www.typescriptlang.org/docs/handbook/2/generics.html) 相关。感叹号称为[非空断言运算符](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator)。 (2认同)