javascript - 如果我想在 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
我将如何在反应中做到这一点?
解决方案
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,
推荐阅读
- windows - 如何更好地处理 CommandBar 中的长项目名称
- python - 如果在循环期间发生异常:如何在传递异常之前返回中间结果?
- android - Android 库模块中的房间数据库设置
- javascript - 加载微调器 div 未及时呈现
- javascript - 错误:在 AWS lambda 函数中使用 ssh2-sftp-client 连接到 SFTP 服务器会引发超时
- python - 是否可以从 Azure Blob 存储容器中读取所有文件,并在使用 Python 读取后删除文件?
- javascript - 如何修复“类型 'Promise<{}>' 缺少来自类型 'Observable 的以下属性
'" 角度 - python - 如何判断一个不存在的路径是否在 Python 中以跨平台的方式指向目录或文件?
- r - 如何使用具有复杂索引进度的 3 个 for 循环来加速此计算?
- javascript - typeScript 函数跳过第一个值为 0 的值