导入 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
调用。因此,只需使用WOW.js 提供的“实时”选项禁用错误:
import { WOW } from "wowjs";
// your class declaration extending React.component...
componentDidMount() {
const wow = new WOW({live: false}); // disables sync requirement
wow.init()
}
现在应该不再有错误,并且动画将在滚动时播放。
相关的 GitHub 问题在这里。
奖励:与问题无关,但 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
}
})
}
感谢 danielgoodwin97 完成了这个简单的修复。