【问题标题】:How can I define the type for a <video> reference in React using Typescript?如何使用 Typescript 在 React 中定义 <video> 引用的类型?
【发布时间】:2021-04-19 19:37:57
【问题描述】:

我正在尝试使用 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; }'

【问题讨论】:

  • 这是一个&lt;video&gt; 元素。不要使用src 属性,使用<source> 元素。此外,如果这是实际的 React,请使用 createRef 创建一个 ref。
  • @Mike'Pomax'Kamermans useRefcreateRef 的钩子版本。

标签: html reactjs typescript dom use-ref


【解决方案1】:

要设置 ref 的类型,您可以像这样设置类型:useRef&lt;HTMLVideoElement&gt;()。然后,要处理对象可能是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 的示例反应应用程序中看到了这个 useRef&lt;HTMLVideoElement&gt;(null!) 语法,只是无法弄清楚这个语法。我以前从未见过这个,并且在 React 文档中找不到它。你有更多关于它的信息的来源吗?谢谢
  • @Panpaper useRef 是一个 React 钩子。 useRef(null) 将其值初始化为 null。 useRef&lt;HTMLVideoElement&gt;(null) 是 TypeScript,它告诉编译器存储在 ref 中的值是 HTMLVideoElement 类型。 &lt;&gt;generics 相关。感叹号称为non-null assertion operator
  • @Panpaper 不确定是否!那里需要。可能取决于您的 TypeScript 版本和 tsconfig 设置。
猜你喜欢
  • 2017-08-31
  • 2020-08-05
  • 1970-01-01
  • 2020-11-19
  • 1970-01-01
  • 2020-10-15
  • 2023-03-15
  • 2019-10-06
相关资源
最近更新 更多