【问题标题】:React video element doesnt pause反应视频元素不会暂停
【发布时间】:2021-10-12 16:58:53
【问题描述】:

嘿,我试图让视频播放器做出反应,并想制作自己的控件,但我遇到了一个问题。handlePlay 是一个 OnClick 函数,应该播放或暂停视频。 isPlaying 是跟踪用户命令的状态(isPlaying 初始化为 true),但即使状态更新,视频也不会暂停。有人可以帮忙吗 谢谢

class Video extends React.Component {
  constructor(...args) {
    super(...args);
    const video = document.createElement("video");
    video.src = Vid;
    video.type = "video/mp4";
 
    this.state = {
      video: video,
      timestamps: [],
      isPlaying: true,
    };

    video.addEventListener("canplay", () => {
      if (this.state.isPlaying === true) {
        console.log("play");
        video.play();
        //this.image.getLayer().batchDraw();
       // this.requestUpdate();
      } else {
        console.log("pause");
        video.pause();
        //this.image.getLayer().batchDraw();
        //this.requestUpdate();
      }
    });
  }

  handlePlay = () => {
 
    if (this.state.isPlaying === true) {
      this.setState({
        isPlaying: false,
      });
    } else {
      this.setState({
        isPlaying: true,
      });
    }
  };

【问题讨论】:

    标签: javascript reactjs html5-video


    【解决方案1】:

    首先,您应该使用 React 组件的 render 方法进行视频渲染,然后挂钩正确的 onClick 处理程序,以便使用自定义控件播放/暂停。代码看起来像这样:

    import React, { Component } from "react";
    
    export default class Video extends Component {
      constructor(props) {
        super(props);
        this.state = {
          timestamps: [],
          isPlaying: true
        };
      }
    
      videoRef = React.createRef();
    
      handlePlay = () => {
        if (this.state.isPlaying === true) {
          this.videoRef.current.pause();
          this.setState({
            isPlaying: false
          });
        } else {
          this.videoRef.current.play();
          this.setState({
            isPlaying: true
          });
        }
      };
    
      render() {
        return (
          <>
            <video
              ref={this.videoRef}
              autoPlay
              src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
            />
            <button type="button" onClick={this.handlePlay}>
              Control
            </button>
          </>
        );
      }
    }
    

    我创建了一个虚拟按钮来模拟您的控制。
    需要videoRef 来保留视频元素的引用,该引用使用ref 属性分配给它,并以videoRef.current 访问。您可以在官方React docs了解更多关于 refs 的信息。

    您可以在以下code sandbox 上找到一个工作示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-04
      • 1970-01-01
      • 1970-01-01
      • 2016-05-12
      • 1970-01-01
      • 1970-01-01
      • 2019-01-09
      相关资源
      最近更新 更多