最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use a React Ref to call video.play()? - Stack Overflow

programmeradmin0浏览0评论

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 ponent:

import React from 'react';
import styled from 'styled-ponents';
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=".png"
          loop
          src=".mp4"
        >
          <track kind="captions" />
        </StyledVideo>

      </Container>
    );
  }
}

export default Video;

Thank you

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 ponent:

import React from 'react';
import styled from 'styled-ponents';
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/videos/homepage/v4/Boards.mp4"
        >
          <track kind="captions" />
        </StyledVideo>

      </Container>
    );
  }
}

export default Video;

Thank you

Share Improve this question asked Nov 5, 2018 at 20:20 AnApprenticeAnApprentice 111k202 gold badges637 silver badges1k bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

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

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

发布评论

评论列表(0)

  1. 暂无评论