GatsbyJS/ReactJS & AOS(滚动动画)导致构建问题

IT技术 css reactjs animate.css gatsby wow.js
2021-05-08 12:28:25

根据 GatsbyJS 的创建者的说法,这似乎是一个常见问题。以下是 GitHub 存储库上已解决问题的引述:

您有引用 window 对象的代码(您自己的或您正在使用的module)。这在服务器渲染时失败,因为您不在浏览器中,因此窗口不存在。这是一个相当普遍的问题。解决方案是在 componentDidMount 中运行对窗口的代码引用,您可以确保您现在在浏览器中。

我只看到了一些在 ReactJS 中设置 AOS 或在 GatsbyJS 中设置类似内容的示例,但没有完全是我需要的。我想出的配置不适用于生产构建又名“gatsby构建”......这是我的代码:

import React from 'react'
import {Link} from 'react-router'
import {prefixLink} from 'gatsby-helpers'
import {config} from 'config'
import AOS from 'aos'

import '../static/css/reset.css'
import '../static/css/typography.css'
import '../static/css/base.css'
import '../static/css/w3.css'
import '../static/css/aos.css'
import '../static/css/devicons.css'

class Template extends React.Component {

componentDidMount() {
  AOS.init()
}

render() {
    const {location, children} = this.props

    return (
        <div>
            <div className='wrapper'>
                {children}
            </div>
        </div>
    );
}

}

Template.propTypes = {
    children: React.PropTypes.any,
    location: React.PropTypes.object,
    route: React.PropTypes.object
}

export default Template

我尝试了一些变体,我将 props 构造函数中的变量设置为 AOS,然后使用 componentDidMount 将变量设置为 AOS.init(),也尝试使用 this.state 并设置它,但都没有任何区别。那么,做所需的正确方法是什么?我知道我将使用 componentDidMount 但除此之外我不知道。任何帮助深表感谢...

2个回答

我终于意识到我忘记了另一个启动 Gatsby 项目是如何处理 Wow.js 的……这就是解决我的问题的方法,基于他们在 Gatstrap、Gatsby 入门博客中的示例:

componentDidMount() {
    const AOS = require('aos');
    this.aos = AOS
    this.aos.init()
}

componentDidUpdate() {
    this.aos.refresh()
}

希望这对其他人有帮助!

我使用 React Hooks (16.8+) 解决了它

let AOS;
  useEffect(() => {
    /**
     * Server-side rendering does not provide the 'document' object
     * therefore this import is required either in useEffect or componentDidMount as they
     * are exclusively executed on a client
     */
    const AOS = require("aos");
    AOS.init({
      once: true,
    });
  }, []);

  useEffect(() => {
    if (AOS) {
      AOS.refresh();
    }
  });