[英]How to use a third party SDK in React
一般來說,我是 React 開發和 web 開發的新手。
有一個由第三方構建的 SDK,可以像下面這樣在“標准 web 開發語言”中下載
HTML 頁:
<script src="https://api.dmcdn.net/all.js"></script>
在我想使用這個第三方 function 的頁面中:
<body>
<div id="player"></div>
用於個性化我從該第三方使用的 object 的代碼部分:
var player = DM.player(document.getElementById("player"),{
video: "x7tgad0",
width: "100%",
height: "100%",
params: {
autoplay: true,
mute: true
}
});
通常,要在 React 中使用第三方“組件”,我使用 npm 安裝下載它。 但是在這里,它不在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 }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.