react 淡入淡出_如何在React with GSAP中创建可重复使用的淡入淡出动画组件

本文介绍了如何利用GSAP库在React中创建一个淡入动画组件。首先讲解了GSAP的基本概念,然后通过设置组件和动画详细阐述了创建过程。文章还展示了如何使动画组件可重用,以便在不同元素上应用。最后提供了如何在项目中使用该淡入组件的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

react 淡入淡出

If you haven't heard about or used GSAP, you're missing out. GSAP is an animation library for components and elements. Their homepage shows a lot of awesome animations you can make with the tool.

如果您没有听说过或未使用过GSAP,那么您就错过了。 GSAP是组件和元素的动画库。 他们的主页显示了您可以使用该工具制作的许多很棒的动画。

GSAP has a lot of configurations, and there's no one right way to achieve one type of animation. So we'll be looking at one way (opinionated) of creating a 'Fade In' animation when a component loads.

GSAP有很多配置,没有一种实现一种动画的正确方法。 因此,我们将研究在组件加载时创建“淡入”动画的一种方法(有针对性)。

This article won't be going into detail about how to use GSAP. Their documentation is the go-to resource if you want an in-depth guide to learn the tool.

本文将不详细介绍如何使用GSAP。 如果您想要深入的指南来学习该工具,那么他们的文档是首选资源。

我们要制作动画的东西 (What we're going to animate)

Here's a little description of what we're going to animate:

这是我们要制作动画的一些描述:

It's something simple. When a component is loaded (wherever), it fades in. We'll also add direction so that the component fades in from area to the normal position.

这很简单。 加载组件(无论在何处)时,它都会淡入。我们还将添加方向,以便组件从区域淡入到正常位置。

We'll also make the animation component reusable so that we can apply it to different elements.

我们还将使动画组件可重用,以便将其应用于不同的元素。

让我们开始吧! (Let's get started!)

GSAP安装 (GSAP installation)

First, you must have a react project set up. create-react-app is there for you if you need to quickly set one up for this project.

首先,您必须设置一个react项目。 如果您需要为此项目快速设置一个create-react-app ,则可以使用它。

To install GSAP, enter the following command in your terminal (with the current directory being your react project directory):

要安装GSAP,请在终端中输入以下命令(当前目录为react project目录):

npm install --save gsap

创建一个可用的动画组件 (Create a Usable Animation Component)

设置组件 (Setting up the component)

Let's call our componet, FadeIn:

我们将其称为FadeIn

import React, {useRef, useEffect} from 'react'

const FadeInAnimation = ({children, wrapperElement = 'div', direction = null, ...props}) => {
  const Component = wrapperElement;
  const compRef = useRef(null)
  useEffect(() => {
    // animations
  }, [compRef])
  return (
    <Component ref={compRef} {...props}>
      {children}
    </Component>
  )
}

export default FadeInAnimation

Our animation isn't ready yet, but let's understand what we're starting with.

我们的动画尚未准备好,但让我们了解一下我们的开始。

  • wrapperElement: used to specify what the component would be. It has a default of div. This is better than creating an extra DOM node to wrap the component we want to animate.

    wrapperElement :用于指定组件将是什么。 它的默认值为div 。 这比创建一个额外的DOM节点来包装我们要设置动画的组件要好。

  • useRef: gsap we need this to know what to trigger animations for. With this, we can refer to our component in the DOM.

    useRefgsap我们需要它来知道触发动画的目的。 这样,我们可以在DOM中引用我们的组件。

  • useEffect: without this, gsap will trigger animations with a null reference (useRef(null)). We have to ensure the component is mounted already, hence this hook.

    useEffect :没有此功能, gsap将触发具有空引用( useRef(null) )的动画。 我们必须确保已安装该组件,因此必须安装此挂钩。

  • children: this will be what's found between <FadeInAnimation> and </FadeInAnimation>. Could be text, or even a group of elements.

    children :这将在<FadeInAnimation></FadeInAnimation>之间找到。 可能是文本,甚至是一组元素。

  • ...props: to extend reusability, this is necessary so that the components can apply other props like className and style.

    ...props :为了扩展可重用性,这是必需的,以便组件可以应用其他props(例如classNamestyle

  • direction: for cases where we want to add direction to the fade-in effect. The default value is null.

    direction :用于我们要为淡入效果添加方向的情况。 默认值为空。

Now let's head over to GSAP.

现在,让我们转到GSAP。

设置动画 (Setting up the animation)
import React, { useRef, useEffect } from "react";
import { gsap } from "gsap";

const FadeInAnimation = ({
  children,
  wrapperElement = "div",
  direction = null,
  delay = 0,
  ...props
}) => {
  const Component = wrapperElement;
  let compRef = useRef(null);
  const distance = 200;
  let fadeDirection;
  switch (direction) {
    case "left":
      fadeDirection = { x: -distance };
      break;
    case "right":
      fadeDirection = { x: distance };
      break;
    case "up":
      fadeDirection = { y: distance };
      break;
    case "down":
      fadeDirection = { y: -distance };
      break;
    default:
      fadeDirection = { x: 0 };
  }
  useEffect(() => {
    gsap.from(compRef.current, 1, {
      ...fadeDirection,
      opacity: 0,
      delay
    });
  }, [compRef, fadeDirection, delay]);
  return (
    <Component ref={compRef} {...props}>
      {children}
    </Component>
  );
};

export default FadeInAnimation;

Let's go over what happened here:

让我们回顾一下这里发生的事情:

  • We initialized a variable distance to be 200. This is useful for cases where a direction is applied. You can also add this to the input props so that the component using it can decide.

    我们将可变distance初始化为200。这对于应用方向的情况很有用。 您也可以将其添加到输入道具,以便使用它的组件可以确定。

  • We have our switch case. This is to determine the direction of the fade-in, with the default case for cases where the direction is not specified.

    我们有我们的switch盒。 这是确定淡入的方向,对于未指定方向的情况为默认情况。

  • Then gsap. This is exposed from GSAP to animate our component. There's .to, .from, .fromTo and more you can find in the docs.

    然后gsap 。 这是从GSAP公开的,以使我们的组件动起来。 有.to.from.fromTo多,你可以在文档中找到。

  • gsap.from in our case refers to the initial state of the component before the final one (set in the component's stylesheet). We target the current element of the ref, apply a duration of 1 second, and apply the animation options.

    在我们的例子中, gsap.from指的是组件的初始状态,而不是最终状态(在组件的样式表中设置)。 我们以ref的当前元素为目标,应用1秒钟的持续时间,并应用动画选项。

  • ...fadeDirection: we spread the object so it appears there as {x: 200} or as specified. x is for horizontal and y is for vertical.

    ...fadeDirection :我们传播对象,使其在此处显示为{x: 200}或指定的位置。 x是水平的, y是垂直的。

  • Then, an initial opacity of 0 and a delay as specified by the component.

    然后,初始不透明度为0,并由组件指定了延迟。

And that's it. Let's make a component that uses this awesome animation.

就是这样。 让我们制作一个使用该超棒动画的组件。

如何使用我们可恢复的淡入组件 (How to use our resuable fade in component)

Head over to the component you want to animate and do something similar to the following:

转至要设置动画的组件,然后执行以下操作:

import React from "react";
import FadeInAnimation from "./FadeInAnimation";

export default function App() {
  return (
    <div>
      <FadeInAnimation wrapperElement="h1" direction="down">
        Hello CodeSandbox
      </FadeInAnimation>
      <FadeInAnimation wrapperElement="h2" direction="right" delay={2}>
        Start editing to see some magic happen!
      </FadeInAnimation>
      <FadeInAnimation
        style={{
          width: 200,
          color: "white",
          height: 200,
          backgroundColor: "purple"
        }}
        direction='up'
      >
        <p>Hello</p>
      </FadeInAnimation>
    </div>
  );
}

As seen above, our FadeInAnimation component can accept a style prop. Remember we did ...props.

如上所示,我们的FadeInAnimation组件可以接受style道具。 记住我们做了...props

Here's the result in CodeSandBox

这是CodeSandBox中的结果

结语 (Wrap up)

That's a wrap. This is a simple (opinionated) usage of GSAP for fade-in effects.

这是一个包装。 这是用于淡入效果的GSAP的简单用法(经过修饰)。

Of course, you can configure it further, like making a fade-in bounce effect, fade-in rotate, and other fun things. But I hope this article has given you a brief and concise introduction to how awesome GSAP is and how to get started doing amazing things on the web.

当然,您可以对其进行进一步配置,例如制作淡入弹跳效果,淡入旋转,以及其他有趣的事情。 但是,我希望本文能为您简要扼要地介绍GSAP的出色表现,以及如何开始在网络上进行出色的工作。

Side note: this is similar to the setup I'm using in a new animation package I'm launching soon. I'll share it in this article when it's published : )

旁注:这与我即将启动的新动画程序包中使用的设置相似。 我将在本文发表时分享它:)

翻译自: https://www.freecodecamp.org/news/how-to-create-a-reusable-fade-in-animation-component-in-react-with-gsap/

react 淡入淡出

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值