如何在没有外部库的情况下在React中播放/暂停视频?

Joj*_*joD 8 reactjs

我的网页上有一个视频标签()和一个"播放/暂停"按钮,当用户点击它时,视频开始/停止播放.如果我不允许使用js来调用"getElementById"然后使用play()/ pause()内置方法,我怎么能做出反应呢?任何的想法?

mhe*_*ers 17

React 函数组件的更新示例:

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


Run Code Online (Sandbox Code Playgroud)


Bra*_*rst 14

最直接的方法是使用refsReact功能,它允许您调用从a返回的组件实例上的方法render().

您可以在文档中阅读更多内容:https://facebook.github.io/react/docs/more-about-refs.html

在这种情况下,只需refvideo标签中添加一个字符串,如下所示:

<video ref="vidRef" src="some.mp4" type="video/mp4"></video>
Run Code Online (Sandbox Code Playgroud)

这样,当您向按钮添加点击处理程序时:

<button onClick={this.playVideo.bind(this)}>PLAY</button>
Run Code Online (Sandbox Code Playgroud)

playVideo方法可通过refs以下方式访问您的视频参考:

playVideo() {
  this.refs.vidRef.play();
}
Run Code Online (Sandbox Code Playgroud)

这是一个有效的DEMO,所以你可以查看一个完整的例子.


Hit*_*ahu 5

接受的答案是使用旧的反应风格,如果你想用 ES6

自动播放暂停以及手动控制播放 Polestar 介绍的简单组件:

    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;
Run Code Online (Sandbox Code Playgroud)

视频来自https://www.polestar.com/cars/polestar-1