Next.js(React)和ScrollMagic

JavaScript React.js

西门

2020-03-20

我想实现一个动画来淡化本示例中的部分,使其进入我的应用程序。因此,我看了一下fullPage.js。

但是,由于我需要将其集成到具有服务器端渲染功能Next.js React应用中,因此我无法使用它,因为它在不支持SSR的jQuery上进行中继。因此,我尝试了ScrollMagic的运气,它不依靠jQuery。但是,这也并不支持SSR(需求window),因此我在初始化它componentDidMount()的方法,甚至装好了那里(就像它的建议在这里)。

它目前最初可以正常工作,但是一旦您更改页面并完成AJAX请求并且Next.js替换页面,就会引发错误(请参见下文):

找不到节点

将ScrollMagic与Next.js一起使用时未找到Node React错误

我曾尝试在中的AJAX请求之前销毁ScrollMagic componentWillUnmount(),但是没有运气。我不知道出了什么问题,不幸的是,我找不到关于带有React或Next.js的ScrollMagic的文档。

这是我的整个组件:

import React from 'react';
import PropTypes from 'prop-types';

class VerticalSlider extends React.Component {
  constructor(props) {
    super(props);
    this.ScrollMagic = null;
    this.controller = null;
    this.scenes = [];
    this.container = React.createRef();
  }

  componentDidMount() {
    if (this.container.current) {
      // Why "require" here?
      // https://github.com/zeit/next.js/issues/219#issuecomment-393939863
      // We can't render the component server-side, but we will still render
      // the HTML
      // eslint-disable-next-line global-require
      this.ScrollMagic = require('scrollmagic');
      this.initScroller();
    }
  }

  componentWillUnmount() {
    this.scenes.forEach(scene => {
      scene.destroy();
    });
    this.controller.destroy();
    this.scenes = [];
    this.controller = null;
  }

  initScroller() {
    try {
      this.controller = new this.ScrollMagic.Controller();
      if (this.container.current !== null && this.container.current.children) {
        [...this.container.current.children].forEach(children => {
          const scene = new this.ScrollMagic.Scene({
            triggerElement: children,
            duration: window.innerHeight * 1.5,
            triggerHook: 0,
            reverse: true
          });
          scene.setPin(children);
          this.scenes.push(scene);
        });
        this.controller.addScene(this.scenes);
      }
    } catch (e) {
      console.log(e);
    }
  }

  render() {
    return (
      <div ref={this.container}>
        {this.props.sections}
      </div>
    );
  }
}

VerticalSlider.propTypes = {
  sections: PropTypes.arrayOf(PropTypes.node).isRequired
};

export default VerticalSlider;

第2529篇《Next.js(React)和ScrollMagic》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0个回答

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android