如何使用React Ref调用video.play()?

时间:2018-11-05 20:20:03

标签: javascript html5 reactjs html5-video

如何使用ref触发video.play()?

当前我遇到错误:preview.bundle.js:261916 Uncaught TypeError: _this2.videoRef.play is not a function

这是我的组件:

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;

谢谢

1 个答案:

答案 0 :(得分:1)

console.log(this.videoRef.props.children);组件的<Waypoint />回调中删除onEnter,您应该可以正常播放视频。

有关工作示例,请参见此https://codesandbox.io/s/nwqwopj1p0链接。