javascript - 在 react 中加载脚本

标签 javascript reactjs

我正在尝试在 React 中加载脚本,而不是将其绑定(bind)到 HTML 文件中。我就在附近,无法正常工作。

我的 html 文件:

<!DOCTYPE html>
<html lang="en">
    <head>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta name="google-signin-client_id" content= "817677528939-dss5sreclldv1inb26tb3tueac98d24r.apps.googleusercontent.com">

        <meta name="google-signin-scope" content="profile email">
        <script src="https://apis.google.com/js/platform.js"></script>
        <title>React App</title>
    </head>
    <body>

        <div id="root"></div>
    </body>
</html>

这行得通。但我试图让它在不包含在 HTML 文件中的情况下工作。

加载脚本

const loadScript = (url) => new Promise((resolve, reject) => {
  let ready = false;
  if (!document) {
    reject(new Error('Document was not defined'));
  }
  const tag = document.getElementsByTagName('script')[0];
  const script = document.createElement('script');

  script.type = 'text/javascript';
  script.src = url;
  script.async = true;
  script.onreadystatechange = () => {
    if (!ready && (!this.readyState || this.readyState === 'complete')) {
      ready = true;
      resolve(script);
    }
  };
  script.onload = script.onreadystatechange;

  script.onerror = (msg) => {
    console.log(msg);
    reject(new Error('Error loading script.'));
  };

  script.onabort = (msg) => {
    console.log(msg);
    reject(new Error('Script loading aboirted.'));
  };

  if (tag.parentNode != null) {
    tag.parentNode.insertBefore(script, tag);
  }
});


export default loadScript;

然后在我的 App.js 中

loadScript() {
// Load the google maps api script when the component is mounted.

    loadScript("https://apis.google.com/js/platform.js")
        .then((script) => {
        // Grab the script object in case it is ever needed.
            this.script = script;
            this.setState({ apiLoaded: true });
        })
        .catch((err: Error) => {
            console.error(err.message);
        });
}


componentDidMount() {
        console.log('component did mount')

        this.loadScript()

        ///how do I make this gapi below reference gapi inside this.script?
        gapi.load('auth2', () => {
            var auth2 = gapi.auth2.init({
                client_id: '817677528939-dss5sreclldv1inb26tb3tueac98d24r.apps.googleusercontent.com',
                scope: 'profile email',

            })
            .then((auth2) => {
                if (auth2.isSignedIn.get()) {
                    this.setState({
                        redirect:true,
                        gapiLoaded:true
                    })
                } else {
                    console.log( "signed in: " + auth2.isSignedIn.get())
                    this.setState({
                        gapiLoaded: true
                    },
                    () => {console.log('state set')})    
                }

            });
        });
    }

打印gapi

{platform: {…}, _pl: true, additnow: {…}, backdrop: {…}, load: ƒ, …}

打印响应

<script type="text/javascript" src="https://apis.google.com/js/platform.js" async="" gapi_processed="true"></script>

看起来它正在打印出元素。然后如何访问其中的 gapi

最佳答案

我认为您希望在 gapi 可用时使用它。您可以随机播放代码。您等到使用 loadScript 加载它。

App.js - React 组件

loadScript(){
  loadScript("https://apis.google.com/js/platform.js")
    .then((script) => {
      /* setState stuff */
      this.gapiLoad(); // use gapi api, it is now available
    })
}

gapiLoad(){
  window.gapi.load('auth2', () => {
    /* your code */
  })
}

componentDidMount(){
  this.loadScript();
}

或者,您也可以使用生命周期 componentDidUpdate 并测试 apiLoaded 为真而 gapiLoad 为假。然后使用gapi api。

关于javascript - 在 react 中加载脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47477720/

相关文章:

javascript - Angular:如何从 elementRef 判断元素是否已给定类应用于它?

javascript - 当我更新数据库中的用户文档时,Meteor 用户被注销

javascript - 如何使 React 多步骤表单与 React Router 一起工作?

javascript - Firebase-Admin,导入它以 react 应用程序抛出模块未找到错误

javascript - 当我单击 react native 中的列表项时如何更改文本?

javascript - 如何在 React 中使用 useState 检查复选框的更改值

javascript - 如何使 Javascript 文件使用发送到 Pug View 的变量

javascript - 在 html 页面上嵌入 Web-GL 沙箱的效果

javascript - 不打印控制台日志

javascript - 尽管收到有效的操作有效负载(异步身份验证调用),为什么我的 Redux 状态没有更新