首页 > 解决方案 > TypeScript React - 通过 ref 访问视频元素并调用 .play()

问题描述

我有一个想要在点击时播放的 TypeScript React 视频组件。我希望通过使用单击处理程序来执行此操作,该处理程序通过 ref 访问视频并调用 .play(),但是我收到此错误:

TS2339: Property 'play' does not exist on type 'RefObject<HTMLVideoElement>'.

这是我的代码(省略了不相关的部分):

class FullBleedVideo extends React.Component<PropDef, StateDef> {
  private fullBleedVideo: React.RefObject<HTMLVideoElement>;

  constructor(props: PropDef) {
    super(props);

    this.fullBleedVideo = React.createRef();
    this.state = {
      isPlaying: false,
    };
  }

  public handleVideoClick() {
    this.setState({ isPlaying: true });
    this.fullBleedVideo.play();
  }

  render() {
    const { isPlaying } = this.state;

    return (
      <div className="video_container" onClick={this.handleVideoClick.bind(this)}>
        <video
          ref={this.fullBleedVideo}
        >
          <source src={src} type="video/mp4" />
        </video>
      </div>
    );
  }
}

我对 TypeScript 很陌生,但不确定我哪里出错了?

标签: reactjstypescript

解决方案


this.fullBleedVideo.current.play(); 将工作。您可以通过current属性访问 DOM。

https://reactjs.org/docs/refs-and-the-dom.html


推荐阅读