React中使用Wow.js报错:Uncaught TypeError: Cannot set properties of undefined
Vite项目中wow.js报错的解决方法
问题原因
- 模块导入不兼容:wowjs v1.1.3基于CommonJS编写,Vite的ES模块导入逻辑下,直接
import WOW from "wowjs"无法正确获取构造函数。 - animate.css版本不匹配:你使用的animate.css 4.x采用
animate__前缀类名规范,而wowjs默认适配3.x版本的animated基础类,导致动画逻辑冲突。
修复步骤
1. 修正导入与初始化代码
任选以下一种方式调整:
方案A:导入编译后的ES版本
import WOW from 'wowjs/dist/wow.js'; useEffect(() => { new WOW({ live: false, animateClass: 'animate__animated' // 适配animate.css 4.x }).init(); }, []);
方案B:适配CommonJS导出
import WOW from 'wowjs'; useEffect(() => { new WOW.default({ // 需通过.default访问构造函数 live: false, animateClass: 'animate__animated' // 适配animate.css 4.x }).init(); }, []);
2. 确认元素类名规范
动画元素需保留wow触发类,同时使用animate.css 4.x的前缀类:
<div className="homeSec__center wow animate__fadeIn" data-wow-duration="1.5s"></div>
可选优化
如果使用TypeScript,安装类型声明文件获得代码提示:
npm install --save-dev @types/wowjs
内容的提问来源于stack exchange,提问作者Martin Galenda
相关产品推荐
相关产品推荐

