为什么playing={false}时react-player仍播放?搭配antd Modal的问题解决
问题根因
Ant Design 的 Modal 组件默认关闭时仅通过 display: none 隐藏 DOM 节点,不会销毁内部挂载的子组件。你遇到的问题是部分视频源(尤其是Youtube这类第三方嵌入源)的内核没有正确响应 playing 属性的状态变更,导致组件隐藏后仍在后台播放音频。
解决方案
方案1(最便捷):开启Modal关闭销毁属性
直接给Modal添加 destroyOnClose 属性,关闭弹窗时会自动销毁内部的所有子组件,播放器实例直接被卸载,自然会停止播放:
修改你的 getIntroVideoModal 方法里的Modal配置即可:
getIntroVideoModal = () => { return ( <Modal title={null} footer={null} visible={this.state.isModalOpen} onCancel={this.ConfirmationModalhandleCancel} width="fit-content" bodyStyle={{ padding: '0' }} {/* 新增下面这行配置 */} destroyOnClose={true} > {this.getVideo()} </Modal> ) }
注意:该方案每次打开弹窗都会重新加载视频资源,如果需要保留上次观看进度,建议使用方案2。
方案2(保留组件实例,手动控制播放)
如果你需要保留播放器的观看进度等状态,不想关闭弹窗就销毁组件,可以通过ref获取react-player实例,关闭弹窗时手动调用暂停方法:
- 首先在constructor中初始化ref
constructor(props) { super(props); this.state = { isModalOpen: false, }; // 新增播放器ref this.playerRef = React.createRef() }
- 给ReactPlayer组件绑定ref
getVideo = () => { console.log("Modal state",this.state.isModalOpen) return ( <ReactPlayer ref={this.playerRef} playing={this.state.isModalOpen} className="introductionVideoLearningPlanPage" controls={true} url="https://www.youtube.com/watch?v=agi4geKb8v8" /> ); };
- 关闭弹窗时手动触发暂停
ConfirmationModalhandleCancel = () => { // 先暂停播放器 this.playerRef.current?.pause() this.setState({ isModalOpen: false }); };
内容的提问来源于stack exchange,提问作者era s'q
相关产品推荐
相关产品推荐

