带有 React 17 的机车滚动

时间:2021-01-22 13:24:10

标签: reactjs parallax locomotive-scroll

我正在尝试将 Locomotive Scroll 与 React 17 结合使用。我不知道如何正确设置组件以使其正常工作。我找到的所有示例都是针对旧版本的 React,我不明白。

有谁知道如何让它发挥作用?

我认为它应该是这样的:

import React from "react"
import LocomotiveScroll from "locomotive-scroll"


const ComponentName = () => {

 //some code here

  return (
      <div data-scroll-container>
        <section data-scroll-section>
          <h1 data-scroll>Hey, there!</h1>
          <p
            role="img"
            aria-label=""
            data-scroll
            data-scroll-direction="horizontal"
            data-scroll-speed="3"
          >
            ?
          </p>
        </section>
        <section data-scroll-section>
          <h2 data-scroll data-scroll-speed="1">
            What's up?
          </h2>
          <p data-scroll role="img" aria-label="">
            ?
          </p>
        </section>
      </div>
    );
  }

export default ComponentName

2 个答案:

答案 0 :(得分:0)

你绝对应该做的是创建一个实例: https://github.com/locomotivemtl/locomotive-scroll#with-a-bundler

答案 1 :(得分:0)

您应该在 useEffect 中使用它,如下例所示。 您可以尝试通过直接获取类或使用 useRef 来使用它。 试试看下面的例子。

    import LocomotiveScroll from 'locomotive-scroll';
    import { useEffect, useRef } from 'react';
    
    export default function Home() {
    
       let container = useRef(null);
    
       useEffect(() => {
          
          new LocomotiveScroll({
             el: container,
             smooth: true,
             lerp: .06,
             multiplier: .5
          });
    
       }, []);
    
       return (               
          <div ref={el => container = el} className="container">
             <div data-scroll data-scroll-speed="1">
               //Code here
             </div>
          </div>
       )
    }
相关问题