首页 > 解决方案 > 如何在 React Web 应用程序中加载 JavaScript 文件并调用 JS 函数?

问题描述

我正在调用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 web page 调用同样的 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;

你能帮我理解如何调用上面代码中的函数吗?还有比我在这里所做的更好的方法吗?

标签: javascripthtmlreactjsuse-effectonload

解决方案


这就是我使用自己的 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

应用程序.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;

推荐阅读