【问题标题】:ReactJS with wowJS not working带有 wowJS 的 ReactJS 不起作用
【发布时间】:2016-12-07 21:34:01
【问题描述】:

我似乎无法让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

卡在那里:(

【问题讨论】:

标签: javascript reactjs npm wow.js


【解决方案1】:

你应该写:

import WOW from 'wowjs';

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

注意 WOW() 之前的 WOW。

【讨论】:

  • 这也不起作用。我只是使用了简短的new WOW.WOW().init(),但它仍然不起作用。我可以在渲染的 html 中看到确实添加了动画类,但是动画没有运行。
【解决方案2】:

导入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.

【讨论】:

    【解决方案3】:

    你可以这样导入:

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

    或者如果你想在任何地方使用它,可以这样定义:

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

    【讨论】:

      猜你喜欢
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      • 2019-06-11
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 2017-03-21
      • 2016-06-04
      相关资源
      最近更新 更多