简体   繁体   中英

How to use a React Ref to call video.play()?

how can I use a ref to trigger video.play() ?

Currently I'm getting an error: preview.bundle.js:261916 Uncaught TypeError: _this2.videoRef.play is not a function

Here is my component:

import React from 'react';
import styled from 'styled-components';
import Waypoint from 'react-waypoint';

const Container = styled.div`
  position: relative;
  padding-top: 64px;
`;

const StyledVideo = styled.video`
  width: 500px;
`;


class Video extends React.Component {
  handleRef = (video) => {
    this.videoRef = video;
  };

  render() {
    return (
      <Container>
        <Waypoint
          onEnter={() => {
            console.log(this.videoRef.props.children);
            this.videoRef.play();
          }}
        />
        <StyledVideo
          ref={this.handleRef}
          muted
          playsinline
          poster="https://luna1.co/88dbde.png"
          loop
          src="https://d1gwm4cf8hecp4.cloudfront.net/videos/homepage/v4/Boards.mp4"
        >
          <track kind="captions" />
        </StyledVideo>

      </Container>
    );
  }
}

export default Video;

Thank you

Remove console.log(this.videoRef.props.children); from the <Waypoint /> component's onEnter callback, and you should find the video plays as expected.

For a working example, see this https://codesandbox.io/s/nwqwopj1p0 link.

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