javascript - 读取javascript脚本index.html公共(public)文件夹中的类react js

标签 javascript reactjs

我需要知道如何将index.html公共(public)文件夹文件中的javscript脚本嵌入到react组件中。我已经使用了这个方法,但类仍然未定义。

componentDidMount () {
    this._loadScript('/library/es6-shim.js', false)
    this._loadScript('/library/fingerprint.sdk.min.js', true)
    this._loadScript('/library/websdk.client.bundle.min.js', false)
    var script = document.createElement('script')
    script.async = true
    script.innerHTML = "this.sdk = new Fingerprint.WebApi;"
    document.head.appendChild(script)
  }

  _loadScript = (src, type) => {
    var tag = document.createElement('script');
    tag.async = true;
    tag.src = src;
    document.head.appendChild(tag)
    // tag.onload = () => this.scriptLoaded()

    console.log('headers', document.head)
  }

我需要在我的组件中读取新的 Fingerprint.WebApi 实例。

最佳答案

您应该加载所有三个库,然后您应该可以访问全局公开的 Fingerprint 类。

componentDidMount() {
  Promise.all([
      this._loadScript('/library/es6-shim.js'),
      this._loadScript('/library/fingerprint.sdk.min.js'),
      this._loadScript('/library/websdk.client.bundle.min.js')
  ])).then(() => {
    // Fingerprint should be available on the window.
    console.log(window.Fingerprint);
    const sdk = new window.Fingerprint.WebApi();
  });
}
_loadScript = (src) => {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('async', 'true');
    script.setAttribute('src', url);
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });
}

关于javascript - 读取javascript脚本index.html公共(public)文件夹中的类react js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60054309/

相关文章:

javascript - JQuery UI 可排序 - 可以取消特定元素吗?

javascript - React - 如何填充并显示模态框,然后在提交时发送 AJAX 请求

reactjs - 在 react 应用程序中拦截返回事件以确认保存

reactjs - this.handleClick 与 this.handleClick()

javascript - 火力地堡、Auth0、 react 。自定义 token 格式不正确。请检查文档

javascript - 使变量对用户完全不可见,直到他做了特定的事情

javascript - 谷歌地图 API 缩放条不显示

javascript - 通过触发器实例化 Backbone? (或者如何推迟匿名函数的执行?)

javascript - 如何将ajax数据传递给react中的组件

javascript - 使用 aimaraJS 创建树结构如何获取选择的特定节点来执行 API 操作?