问题描述
我正在调用 JavaScript SDK 并在我的 HTML 代码中按照以下方式调用它的函数,它按预期工作正常。
这是代码
<!DOCTYPE html>
<head>
<title>My Test App</title>
<script src="scripts/abc.js"></script>
<script src="scripts/xyz.js" onload="initXYZ('Param1')"></script>
</head>
</html>
现在,我想从 React 网页调用相同的 Javascript SDK。我想调用脚本并调用 initXYZ('Param1') 函数。
到目前为止,我能够加载 SDK,但我不确定如何像上面那样调用该函数。这是我在 react app 中写的代码。
import React,{useEffect,useRef} from "react";
import "./App.css"
const App = () => {
const instance = useRef(null);
useEffect(() => {
const settingsTag = document.createElement("script");
settingsTag.src = "scripts/abc.js";
instance.current.appendChild(settingsTag);
const websdkTag = document.createElement("script");
websdkTag.src = "scripts/xyz.js";
instance.current.appendChild(websdkTag);
},[]);
return (
<>
<h1>My React app</h1>
<div ref={instance} >
</>
);
};
export default App;
你能帮我理解如何调用上面代码中的函数吗?还有比我在这里所做的更好的方法吗?
解决方法
这就是我使用自己的 SDK 所做的。
只需在所需的 SDK 中创建尽可能多的类即可。 将所有这些子 SDK 嵌入到您从应用程序引用的对象 SDK 中。 看看它的样子:
SDK.js
// From here,pretend the following is the content of your sdk.js
class SdkAbc {
static shared // The singleton
constructor() {
// If already created,returned the singleton
if (SdkAbc.shared) return SdkAbc.shared
// Actually create the instance
SdkAbc.shared = this
// You might want to write your init code right below
}
version() {
return 1.3
}
}
class SdkXyz {
// Same as above
}
// You SDK singleton can host as many SDK sections as you need
const Sdk = {
abc: new SdkAbc(),xyz: new SdkXyz(),}
export default Sdk
App.js
import React,{useEffect,useRef} from "react";
import "./App.css"
import sdk from './sdk/sdk' // provided sdk.js is your sdk file located in /sdk folder
const App = () => {
return (
<>
<h1>My React app</h1>
<div>Sdk Abc version: {Sdk.abc.version()} >
</>
);
};
export default App;
,
您可以使用 react-helmet 将任何 js 文件添加到页面