发布于 2026-01-06 4 阅读
0

在 Next.js 中使用 React-Scroll-Parallax 实现视差效果 😉 由 Mux 主办的 DEV 全球展示挑战赛:展示你的项目!

在 Next.js 中使用 React-Scroll-Parallax 实现视差效果 😉

由 Mux 主办的 DEV 全球展示挑战赛:展示你的项目!

视差是一种非常酷炫的效果,可以通过改变背景图层的速度来实现。

图片描述

今天我们来探索如何使用名为 react-scroll-parallax 的包在 Next.js 中实现类似的视差效果🥰。

图片描述

https://react-scroll-parallax.damnthat.tv/docs/intro



npm i react-scroll-parallax


Enter fullscreen mode Exit fullscreen mode

让我们使用 create-next-app 初始化我们的项目。



npx create-next-app --example with-tailwindcss parallax


Enter fullscreen mode Exit fullscreen mode

我在YouTube上做了一个完整的教程,你也可以去看看。

现在让我们继续我们的博客。

首先,请将所有 TypeScript 文件替换为 JavaScript,因为初始模板默认配置的是 TypeScript 😞 或者您也可以在 TypeScript 文件中编写普通的 JavaScript 代码 😲 这也没什么大不了的。

首先,将我们的组件包裹在 _app.js 中,并使用 ParallaxProvider 进行封装。由于我们要创建水平滚动视差效果,因此必须指定 scrollAxis='horizo​​ntal'。



import '../styles/globals.css'
import { ParallaxProvider } from 'react-scroll-parallax'

function MyApp({ Component, pageProps }) {
  return (
    <ParallaxProvider scrollAxis='horizontal'>
      <Component {...pageProps} />
    </ParallaxProvider>
  )
}

export default MyApp


Enter fullscreen mode Exit fullscreen mode

我们想要的最终效果是这样的👇🏻

图片描述

场景主体部分包含火车、云朵和太阳等组件。我们希望火车和云朵相对于背景图像移动,而太阳保持静止。为此,我们将使用 react-scroll-parallax 中的 useRef 和 useParallax 组件。首先,创建一个 const target 来存储最外层的 div 元素。然后,使用 useParallax 为内部的 div 元素创建 ref,并在 useParallax 中传递 speed 和 targetElement 参数。以下是代码👇🏻



import { useParallax } from "react-scroll-parallax";
import React, { useRef } from "react";
import Image from "next/image";

const index = () => {
  const target = useRef(null);
  const train = useParallax({
    speed: 500,
    targetElement: target.current,
  })

  const cloud = useParallax({
    speed: 200,
    targetElement: target.current,
  })

  return (
    <div ref={target} style={{
      backgroundImage: "url('/Scene.png')",
      backgroundSize: "cover",
      backgroundPosition: "center",
      width: '3000px'
    }} className="h-screen">
      <div className="fixed top-10 left-40">
        <Image src="/Sun.png" height={120} width={120} />
      </div>
      <div ref={train.ref} className="absolute"
        style={{
          top: '11vh',
          left: '30vw',
        }}
      >
        <Image src="/Train.png" height={350} width={700} />
      </div>
      <div ref={cloud.ref} className="absolute top-10">
        <Image src="/Cloud.png" height={200} width={1000} />
      </div>
    </div>
  );
}
export default index;



Enter fullscreen mode Exit fullscreen mode

完整代码请见 GitHub -> https://github.com/nyctonio/yt-parallax-tutorial

🥳🥳🥳🥳🎊🎊🎊🎊 太棒了!!!!你成功制作出了视差效果!我建议你看看这些资源,学习更多相关知识👇🏻

在 Twitter 上关注我:- Twitter 🤝🏻

欢迎访问我的 GitHub 查看精彩项目:- GitHub 🤝🏻

在领英上联系我:- Linkedin 🤝🏻

请阅读我的另一篇文章:《使用 MongoDB Bcrypt 和 JWT Web Tokens 在 Node.js 中进行身份验证》

一篇博文囊括所有 React Hooks

文章来源:https://dev.to/nyctonio/parallax-in-nextjs-using-react-scroll-parallax-2110