简体   繁体   中英

TypeScript React - access video element by ref and call .play()

I have a TypeScript React video component which I want to play on click. I'm hoping to do this by using a click handler which accesses the video by ref and calls .play(), however I'm getting this error:

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

Here's my code (with irrelevant parts omitted):

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>
    );
  }
}

I'm quite new to TypeScript, but not sure where I've gone wrong?

this.fullBleedVideo.current.play(); will work. You can access DOM via current property.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM