我正在调用一个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。我希望调用脚本并调用initXYZ('Param1')函数。
到目前为止,我能够加载SDK,但我不知道如何像上面那样调用函数。这是我在react应用程序中编写的代码。
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;
请您帮助我理解如何在上面的代码中调用函数。还有什么更好的方法来解决我在这里做的事?
发布于 2021-07-02 15:59:18
这就是我用自己的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 SdkApp.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;发布于 2021-07-07 06:53:58
您可以使用反应头盔将任何js文件添加到页面中。
https://stackoverflow.com/questions/68178634
复制相似问题