如何在 React 中使用第三方 SDK

问题描述

我是 React 开发和网络开发的新手。

有一个由第三方构建的 SDK,可以使用“标准 Web 开发语言”下载,如下所示

HTML 页面:

<script src="https://api.dmcdn.net/all.js"></script>

在我想使用这个第三方功能的页面中:

<body>
<div id="player"></div>

用于个性化我正在使用的第三方对象的代码部分:

var player = DM.player(document.getElementById("player"),{ 
video: "x7tgad0",width: "100%",height: "100%",params: { 
    autoplay: true,mute: true 
} 

});

通常,为了在 React 中使用第三方“组件”,我使用 npm install 下载它。但是在这里,它不在 npm 中。

你会如何使用它?

谢谢!

问候,

解决方法

我确实找到了解决方案。

这里是主要思想:

为了使用 API 脚本(这是一个视频播放器),我们可以先创建一个 React 组件,然后再使用它。这就是该组件应该如何(在我的解决方案中):

class DMPlayer extends Component {*your code here*}

在组件中你需要一个渲染方法:

render () {  return (<div id="player"></div>);}

此处的 div 具有 API/SDK 将指向的 id。但这取决于您要使用的 API/SDK。

让我解决这个问题的主要信息是在 COMponentDidMount 方法中使用 DOM 和 window 如下:

componentDidMount() {
    const DM = document.createElement('script');
    DM.setAttribute('src','https://api.dmcdn.net/all.js');

    let player //we define a variable here but we put something in it after as the code has to donwload first

    DM.addEventListener('load',() => {
      player = window.DM.player //Here we use the window to recover the downloaded script

      player(document.getElementById("player"),{ 
        video: "x7tgad0",width: "100%",height: "100%",params: { 
            autoplay: true,mute: true 
        } 
      }); 
      
    });
  
    document.body.appendChild(DM); //add everithing to the DOM
  }

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...