简体   繁体   English

如何在 React 中使用第三方 SDK

[英]How to use a third party SDK in React

I am new in React dev and web dev in general.一般来说,我是 React 开发和 web 开发的新手。

There is an SDK that has been built by a third party and that would be downloadable like the following in a "standard web development language"有一个由第三方构建的 SDK,可以像下面这样在“标准 web 开发语言”中下载

HTML Page: HTML 页:

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

In the page where I want to use this third party function:在我想使用这个第三方 function 的页面中:

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

The code part to personalize the object I am using from that third party:用于个性化我从该第三方使用的 object 的代码部分:

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

}); });

Usually, to use a third-party "Component" in React, I download it using npm install.通常,要在 React 中使用第三方“组件”,我使用 npm 安装下载它。 But here, it is not in npm.但是在这里,它不在npm中。

How would you do to use it?你会如何使用它?

Thanks!谢谢!

Regards,问候,

I actually found the solution.我实际上找到了解决方案。

Here is the main idea:这是主要思想:

In order to use the API script (which is a video player), we can first create a React component and use it afterwars.为了使用 API 脚本(这是一个视频播放器),我们可以先创建一个 React 组件,然后再使用它。 This is how that component should (in my solution) be:这就是该组件应该如何(在我的解决方案中):

class DMPlayer extends Component {*your code here*}

In the component you will neer a render method:在组件中,您将需要一个渲染方法:

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

The div here has an id to which the API/SDK will point.这里的 div 有一个 API/SDK 将指向的 id。 But this will depend on the API/SDK you want to use.但这取决于您要使用的 API/SDK。

The main information that allowed me to solution this issue is the use of DOM and window in a ComponentDidMount method as follows:允许我解决此问题的主要信息是在 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 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM