how to play/pause video in React without external library?

后端 未结 5 1023

I have a video tag () in my webpage, and a \"play/pause\" button that when the user clicks on it, the video starts/stops playing . How can I do so in react if I\'m not allowed t

相关标签:
5条回答
  • 2021-02-14 00:32

    Updated example for React Function Components:

    import React, { useRef} from 'react'
    
    function myComponent(props) {
      const vidRef = useRef(null);
      const handlePlayVideo = () => {
        vidRef.current.play();
      }
      return (
        <video ref={vidRef}>
          <source src={[YOUR_SOURCE]} type="video/mp4" />
        </video>
      )
    }
    
    
    
    0 讨论(0)
  • 2021-02-14 00:34

    This answer adds to @mheavers, which I upvoted.

    There are a few differences:

    • One can pass noControls as a prop to the Video component, and apply the click event only if the <video> doesn't have the default controls (which will be the case when noControls is passed).
    • The handler function is a toggler; enabling one to play or pause according to its current state.
    • One can create a play button overlay style through the class video__play-button, whilst the same handler hides it through the class is-playing.
    • It also shows how to use two or more ref and pass them as a parameter to a pure render function.
    import React, { useRef } from 'react';
    import PropTypes from 'prop-types';
    
    const renderVideo = ({
      noControls,
      src,
      vidButtonRef,
      vidRef,
      handleToggleVideo,
    }) => (
      <>
        {noControls ? (
          <div ref={vidButtonRef} className="video video__play-button">
            <video
              ref={vidRef}
              src={src}
              onClick={handleToggleVideo}
            ></video>
          </div>
        ) : (
          <video
            src={src}
            controls
            controlsList="nodownload"
          ></video>
        )}
      </>
    );
    
    const Video = props => {
      const vidRef = useRef(null);
      const vidButtonRef = useRef(null);
      const { noControls, src } = props;
      const handlePlay = () => {
        vidRef.current.play();
        // hide overlay play button styles, set by 'video__play-button'
        vidButtonRef.current.classList.add('is-playing');
      };
      const handlePause = () => {
        vidRef.current.pause();
        // show overlay play button styles, set by 'video__play-button'
        vidButtonRef.current.classList.remove('is-playing');
      };
      const handleToggleVideo = () => (vidRef.current.paused ? handlePlay() : handlePause());
      return (
        <>
          {renderVideo({
            noControls,
            src,
            vidButtonRef,
            vidRef,
            handleToggleVideo,
          })}
        </>
      );
    };
    
    Video.propTypes = {
      noControls: PropTypes.bool,
      videoUrl: PropTypes.string,
    };
    
    export default Video;
    
    0 讨论(0)
  • 2021-02-14 00:35

    Use ref attribute to create a link to the video and using that reference we can able to use video controls on the video component

    Try this code,

    import React from "react";
    class VideoDemo extends React.Component {
      
      getVideo = elem => {
        this.video = elem
      }
    
      playVideo = () => {
        this.video.play()
      };
    
      pauseVideo = () => {
        this.video.pause();
      };
    
      render = () => {
        return (
          <div>
            <video
              ref={this.getVideo}
              src="http://techslides.com/demos/sample-videos/small.mp4"
              type="video/mp4"
            />
    
            <div>
              <button onClick={this.playVideo}>
                Play!
              </button>
              <button onClick={this.pauseVideo}>
                Pause!
              </button>
            </div>
          </div>
        );
      };
    }
    
    export default VideoDemo;
    
    0 讨论(0)
  • 2021-02-14 00:36

    Accepted answer was using old react style, if you want to do with ES6

    A simple component to auto play pause along with manual controls playing Polestar intro:

        import React from "react";
        class Video extends React.Component {
          componentDidMount = () => {
            this.playVideo();
          };
    
          componentWillUnmount = () => {
              this.pauseVideo();
          };
    
    
          playVideo = () => {
            // You can use the play method as normal on your video ref
            this.refs.vidRef.play();
          };
    
          pauseVideo = () => {
            // Pause as well
            this.refs.vidRef.pause();
          };
    
          render = () => {
            return (
              <div>
                <video
                  ref="vidRef"
                  src="https://assets.polestar.com/video/test/polestar-1_09.mp4"
                  type="video/mp4"
                />
    
                <div>
                  <button onClick={this.playVideo}>
                    Play!
                  </button>
                  <button onClick={this.pauseVideo}>
                    Pause!
                  </button>
                </div>
              </div>
            );
          };
        }
    
     export default Video;
    

    Video from https://www.polestar.com/cars/polestar-1

    0 讨论(0)
  • 2021-02-14 00:51

    The most straightforward way would be to use refs which is a React feature that will let you invoke methods on the component instances that you have returned from a render().

    You can read up a little more on them in the docs: https://facebook.github.io/react/docs/more-about-refs.html

    In this case just add a ref string to your video tag like so:

    <video ref="vidRef" src="some.mp4" type="video/mp4"></video>
    

    That way when you add click handlers to your buttons:

    <button onClick={this.playVideo.bind(this)}>PLAY</button>
    

    The playVideo method will have access to your video reference through refs:

    playVideo() {
      this.refs.vidRef.play();
    }
    

    Here is a working DEMO so you can check out a full example.

    0 讨论(0)
提交回复
热议问题