React自定义视频播放器异常:isPlaying状态更新后视频无法暂停
问题根因
- 你当前的播放/暂停控制逻辑仅绑定在
canplay事件回调中,该事件只会在视频资源完成加载、首次可播放时触发一次。后续修改isPlaying状态时,这段逻辑不会重新执行,自然不会触发视频的播放/暂停操作。 - 额外优化点:不需要将video DOM实例存入React state,state仅用来存储需要触发视图重渲染的数据,DOM引用直接挂载到组件实例属性上即可。
修复方案
使用类组件的componentDidUpdate生命周期钩子监听isPlaying状态的变化,状态变更时直接操作video实例执行对应的播放/暂停方法,修复后代码如下:
class Video extends React.Component { constructor(...args) { super(...args); // video实例直接挂载到组件实例,无需存入state this.video = document.createElement("video"); this.video.src = Vid; this.video.type = "video/mp4"; this.state = { timestamps: [], isPlaying: true, }; // 初始加载完成后根据初始isPlaying状态控制播放 this.video.addEventListener("canplay", () => { if (this.state.isPlaying) { console.log("play"); this.video.play(); // 你原有的batchDraw、requestUpdate逻辑可保留在此 } }); } // 新增生命周期监听isPlaying状态变化 componentDidUpdate(prevProps, prevState) { // 仅当isPlaying状态发生变更时才执行操作 if (prevState.isPlaying !== this.state.isPlaying) { if (this.state.isPlaying) { console.log("play"); this.video.play(); } else { console.log("pause"); this.video.pause(); } // 你原有的batchDraw、requestUpdate逻辑可放在此处执行 } } handlePlay = () => { // 简化状态切换逻辑 this.setState(prev => ({ isPlaying: !prev.isPlaying })); }; }
内容的提问来源于stack exchange,提问作者tanmya
相关产品推荐
相关产品推荐

