导入WOW.js的正确方法(使用npm安装后)是:
import { WOW } from "wowjs";
const wow = new WOW();
wow.init();
但正如你所说,浏览器给出了错误:
MutationObserver is not supported by your browser. WOW.js cannot detect dom mutations, please call .sync() after loading new content.
根据我在网上找到的,sync 函数用于在 JavaScript 框架进行一些动态更改后替换内容时重新初始化 wow.js。但是,只要您的新组件在挂载后再次调用init 函数,您就不需要调用sync。因此,只需使用“实时”选项 provided by WOW.js 禁用错误即可:
import { WOW } from "wowjs";
// your class declaration extending React.component...
componentDidMount() {
const wow = new WOW({live: false}); // disables sync requirement
wow.init()
}
现在应该不会再出现错误,并且动画将在滚动时播放。
Relevant GitHub issue here.
奖励: 与问题无关,但 WOW.js 的一个重要问题是它会扰乱您的 SEO。该库使用visibility: hidden 样式来隐藏您的内容,然后再进行动画处理,但机器人对此存在问题,因此您的页面排名可能会较低。
解决此问题的一种简单方法是在页面未滚动时阻止 WOW.js 初始化。有了这个,机器人可以索引内容并且用户体验完全不受影响(除非你的屏幕顶部有 WOW 元素,在这种情况下用延迟的 CSS 动画替换它们)。
// bonus code that fixes potential SEO issues
import $ from "jquery";
import { WOW } from "wowjs";
// your class declaration extending React.Component...
componentDidMount() {
const wow = new WOW({live: false}); // disables sync requirement
var scrolled = false;
$(window).on('scroll', function() { // jQuery to check for page scroll, you can replace this with an equivalent if you don't like using both jQuery and ReactJS at the same time
if (!scrolled) {
scrolled = true;
wow.init(); // WOW.js initializes only once the page has scrolled
}
})
}
Credit to danielgoodwin97 for this simple fix.