javascript ReactJS与wowJS不工作

pkbketx9  于 2022-12-10  发布在  Java
关注(0)|答案(4)|浏览(309)

我似乎无法让wowJS工作。
我做import WOW from 'wowjs';

componentDidMount() {
  const wow = new WOW();
  wow.init();
}

但我得到了TypeError: _wowjs2.default is not a constructor
如果我做import { WOW } from 'wowjs';
我得到
MutationObserver is not supported by your browser. WOW.js cannot detect dom mutations, please call .sync() after loading new content.
如果我做了

componentDidMount() {
  const wow = new WOW();
  wow.sync();
}

请注意wow.sync()
我得到TypeError: Cannot read property 'nodeType' of undefined
卡在那里:(

e0bqpujr

e0bqpujr1#

你应该写:

import WOW from 'wowjs';

componentDidMount() {
  const wow = new WOW.WOW();
  wow.init();
}

注意WOW()之前的WOW。

qq24tv8q

qq24tv8q2#

导入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。因此,只需使用“live”选项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()
}

现在应该没有更多的错误和动画将发挥滚动。相关的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提供了这个简单的修复。

drnojrws

drnojrws3#

您可以按如下方式导入它:

componentDidMount() {
  const WOW = require('wow.js');
  new WOW().init();
}

或者如果要在任何地方使用它,请按如下方式定义它:

let WOW;

componentDidMount() {
  WOW = require('wow.js');
  new WOW().init();
}
4si2a6ki

4si2a6ki4#

您需要在React中使用wow.js而不是wowjs

npm install wow.js

在代码中

import WOW from 'wow.js'

useEffect(() => {
    const wow = new WOW({ live: false }) // disables sync requirement
    wow.init()
}, [])

相关问题