jtwang7 / React-Note

React 学习笔记
8 stars 2 forks source link

React - 在 React 组件使用外部 CDN #28

Open jtwang7 opened 3 years ago

jtwang7 commented 3 years ago

React - 在 React 组件使用外部 CDN

引用文章:html - 在 React 组件中导入外部 CDN

前言

使用 create-react-app npm 创建的 react 应用程序,基于模块化思想,各 react 组件内部都有自己独立的作用域。因此,我们无法直接调用在 index.html 中引入的 CDN 所创建的方法。

解决方案

step1

/src/public/index.html 中引入外部 CDN:

<head>
  <script src="https://unpkg.com/scrollreveal"></script>
</head>

step2

在 react 组件中,通过 window 对象调用 CDN 方法即可:

// Component.js
function Component (props) {
  // do something ...
  window.Scrollreveal();
}

注意: 必须通过 window 对象调用,原因如下:

  1. CDN 外链下载后,会将方法注册到全局对象,浏览器中即为 window 对象
  2. react 组件中有自己的作用域,因此不能通过缺省 window 来获取 window 对象