首页 > 解决方案 > 如果我想在 React 中使用像 AOS 这样的 JavaScript 库,如何?

问题描述

我想在我的 React 应用程序中使用 JavaScript 库 AOS ( https://michalsnik.github.io/aos/ )。如何将它包含在我的 App.js 文件中?

import React from 'react';
import logo from './logo.svg';
import './App.css';
import 'aos';

function App() {

  AOS.init();

  return (
    <div className="App">
      <header className="App-header">
        <img data-aos={"fade-left"} src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

AOS 需要初始化,所以我觉得我需要像上面代码中那样做一些事情,但是它抛出了一个错误:

无法编译 ./src/App.js 第 8:3 行:'AOS' 未定义 no-undef

我将如何在反应中做到这一点?

标签: javascriptreactjsnpmshared-libraries

解决方案


According to the documentation, You will need to call AOS.init() to initialise it within your component. This can be done within your componentDidMount lifecycle hook.

In addition, you should import it by referencing the defaultExport by doing this import AOS from 'aos';

If you are using class components, this is how your code should look like.

import AOS from 'aos';

componentDidMount() {
  // or simply just AOS.init();
  AOS.init({
    // initialise with other settings
    duration : 2000
  });
}

On the other hand, for functional components,

useEffect(() => {
  AOS.init({
    duration : 2000
  });
}, []);

Do remember to add an empty array as the dependency array such that the useEffect hook will only run once when the component is mounted,


推荐阅读