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

时间:2017-06-03 02:21:18

标签: javascript html reactjs create-react-app

我正在尝试使用我已加载到我的public class Solution { int count; public int threeSumSmaller(int[] nums, int target) { count = 0; Arrays.sort(nums); int len = nums.length; for(int i=0; i<len-2; i++) { int left = i+1, right = len-1; while(left < right) { if(nums[i] + nums[left] + nums[right] < target) { count += right-left; left++; } else { right--; } } } return count; } } 中的脚本标记中的库中的变量作为我的React组件。我正常加载它:

index.html

但是,当我尝试在我的React组件中访问<head> ... <script src="https://cdn.plaid.com/link/v2/stable/link-initialize.js"></script> <!-- gives me the 'Plaid' library --> ... <title>React App</title> </head> 时,它是未定义的。我很困惑,因为如果我在它之前放入一个调试器,我仍然可以访问它。例如,在我的Plaid组件中,我有:

App.js

为什么componentDidMount() { debugger // can access 'Plaid' here Plaid // throws error, 'Plaid' is undefined } 会抛出错误,即使我可以通过调试器访问它?

2 个答案:

答案 0 :(得分:2)

问题是Webpack文件是单独捆绑的,与所需的脚本分开。因此,当您尝试访问全局变量时,它不存在。

如果您想使用<script>,您必须自己自定义您的Webpack配置。这涉及弹出create-react-app并自行管理所有内容。 在执行此操作之前备份您的项目,因为在弹出之后不会再回头!首先运行:

npm run eject

弹出完成后,导航到webpack.config.js并向配置对象添加新密钥:

externals: {

}

externals所做的是从CDN(如Plaid)获取脚本声明的全局变量,并允许它用作项目中的模块。因此,配置如下:

externals: {
    plaid: 'Plaid'
}

这将从CDN获取全局变量Plaid,并将其作为名为plaid的模块提供。然后,您可以在导入后使用Plaid:

const Plaid = require('plaid'); //ES5
import Plaid from 'plaid'; //ES2015

(这些都没有经过测试,风险自负)。如果通过CDN提供NPM包,我更愿意使用它。

答案 1 :(得分:2)

我知道这已经很晚了,但是我在这里回答这个问题,以备将来遇到上述问题的用户使用。

例外答案是集成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等内容加载组件的脚本。