如何在React类组件中嵌入Dailymotion播放器?报错求助
React类组件中集成Dailymotion播放器的问题修复
你的代码核心问题是:异步加载的Dailymotion脚本还未完成加载,就直接调用了window.dailymotion.createPlayer,导致window.dailymotion未定义报错。
修复方案
给动态创建的script标签添加onload回调,确保SDK加载完成后再初始化播放器:
componentDidMount() { this.setState({ test: true }); const script = document.createElement("script"); script.src = "https://geo.dailymotion.com/player"; script.async = true; // 脚本加载完成后再初始化播放器 script.onload = () => { this.playerLoad(); }; document.body.appendChild(script); } playerLoad() { console.log("daily motion player load "); this.player = window.dailymotion .createPlayer("my-dailymotion-player", { video: "x84sh87", }) .then((player) => console.log(player)) .catch((e) => console.error(e)); } // 组件卸载时清理播放器,避免内存泄漏 componentWillUnmount() { if (this.player) { this.player.destroy(); } }
额外注意事项
- 确保组件渲染了id为
my-dailymotion-player的DOM元素,比如在render方法中添加:<div id="my-dailymotion-player"></div> - 避免在componentDidMount中用箭头函数定义方法(语法可行但不符合React类组件常规写法)
- 组件卸载时调用
player.destroy()可清理播放器实例,防止内存泄漏
内容的提问来源于stack exchange,提问作者Linta Rabail
相关产品推荐
相关产品推荐

