javascript - 在 React 组件中使用 index.html 中包含的脚本

标签 javascript html reactjs create-react-app

我正在尝试为我的 React 组件使用我在 index.html 的脚本标签中加载的库中的变量。我已正常加载它:

<head>
  ...
  <script src="https://cdn.plaid.com/link/v2/stable/link-initialize.js"></script>
  <!-- gives me the 'Plaid' library -->
  ...
  <title>React App</title>
</head>

但是,当我尝试在我的 React 组件中访问 Plaid 时,它是未定义的。我很困惑,因为如果我在它之前放入调试器,我仍然可以访问它。例如,在我的 App.js 组件中,我有:

componentDidMount() {
  debugger // can access 'Plaid' here
  Plaid // throws error, 'Plaid' is undefined
}

为什么 Plaid 会抛出错误,即使我可以通过调试器访问它?

最佳答案

我知道这已经晚了,但我在这里为那些在执行上述操作时遇到问题的 future 用户回答这个问题。

异常(exception)的答案是不是集成 Plaid(或 <script> 标签中的任何外部依赖项)的最佳方式。弹出 React 应用程序应该是 avoided可能的话。

更好的解决方案是使用 React built in访问脚本加载的全局变量的方式。您可以通过访问窗口对象 (window.NameOfYourObject) 来执行此操作。在这种情况下,它将是 window.Plaid .

在上面例子的上下文中,这看起来像

this.linkHandler = window.Plaid.create({
   clientName: 'plaid walkthrough demo',
   product: ['transactions'],
   key: 'YOUR KEY',
   env: 'sandbox',
   webhook: this.props.webhook,
   token: this.props.token,
   selectAccount: this.props.selectAccount,
   longtail: this.props.longtail,
   onLoad: this.handleLoad,
   onSuccess: this.handleSuccess,
   onExit: this.handleExit,
 });

将脚本放在头脑中是可行的,但这也是不好的做法。最好使用类似 react-load-script 的组件加载脚本.

关于javascript - 在 React 组件中使用 index.html 中包含的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44339627/

相关文章:

javascript - 处理垂直文本区域

javascript - 如何在 Meteorjs 中提交隐藏输入的值

javascript - 纯初学者 javascript - array 和 map

javascript - 当我的进度条值发生变化时,如何更改 css 渐变值?

html - 正文和背景部分使用 CSS 分开

javascript - 如何根据复选框选择呈现列表?

reactjs - 如何在 Azure 上部署 NextJs SSR React 应用程序

javascript - React-navigation重置说明

javascript - for 循环内的递归函数未按预期工作

javascript - 使用类别过滤器添加数字分页 - javascript