Next.js(React)和ScrollMagic

dud*_*ude 13 javascript animation reactjs scrollmagic next.js

我想实现一个动画来淡化部分,就像在这个例子中一样,淡入我的应用程序.因此我看了一下fullPage.js.

但是,因为我需要将它集成到具有服务器端呈现的Next.js React应用程序中,所以我不能使用它,因为它在jQuery上进行中继,它不支持SSR.因此,我已经尝试过使用ScrollMagic,它不会在jQuery上转发.但它也不支持SSR(需求window),因此我已经在componentDidMount()方法中对其进行了初始化,甚至将其加载到那里(就像这里推荐的那样).

它目前最初工作,但是一旦你更改页面并完成一个AJAX请求并且Next.js替换了页面,就会抛出一个错误(见下文):

找不到节点

找不到节点使用ScrollMagic和Next.js时出现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;
Run Code Online (Sandbox Code Playgroud)

Pau*_*Dyk 3

fullpage.js不是更适合您的需求吗?

您应该能够映射路线,然后使用 app.js 将每张幻灯片构建为页面的占位符

否则,我应该有一个滚动魔法的工作示例,我将寻找存储库并在找到后分享它。

更新:这是使用 fullpage.js 的 next.js示例

但是,由于我需要将其集成到带有服务器端渲染的 Next.js React 应用程序中,所以我无法使用它,因为它依赖于 jQuery

fullpage.js 不再依赖于 jquery 并且它也支持 SSR。