Home >CMS Tutorial >WordPress >Explore the world of React animation: an introduction

Explore the world of React animation: an introduction

PHPz
PHPzOriginal
2023-09-03 12:25:131292browse

探索 React 动画的世界:简介

When building an application, animations are a great way to improve the overall user experience because they allow for better interaction between the application and the user.

In some of our previous React tutorials, you became familiar with basic React concepts such as JSX, routing, and forms. In this tutorial, we are going to take it to the next level and try to understand animations in React. While there are many ways to add animations to a React application, we will focus in this article on the React Transition Group and how to use it.

Animation in React

React provides many additional utilities for animating React applications, one of which is called React Transition Group, created by the React development team.

It is not a library for setting animation styles; instead, it is a low-level API with four types of built-in components: Transition, CSSTransition, SwitchTransition and TransitionGroup. Therefore, it's very simple to animate React components into and out of the DOM during state changes.

React Transition Group is a very simple tool to get started with, and because it's lightweight, it reduces the need for boilerplate code, speeding up the development process.

start using

First, let's install react using the create-react-app package in the terminal.

npx create-react-app react-animations

Open the index.html file of the public folder and edit the title as follows:

<title>TutsPlus - React Animations</title>

Let’s create a folder called components inside the src folder of our application and create a Home.js file. Next, we update this file by creating a functional component called Home and rendering a h2 tag.

import React from "react";

const Home = () => {
  return (
    <>
      <h2>{"TutsPlus - Welcome to React Animations!"}</h2>
    </>
  );
};

export default Home;

Next, update the App.js file by importing the Home component:

import React from "react";
import Home from "./components/Home";

const App = () => {
  return (
    <>
      <Home />
    </>
  );
};

export default App;

Then, start the development server by running the following command:

npm run start

React Transition Group Settings

Let's first try a simple animation in React by installing the react-transition-group package into the project.

npm install react-transition-group

Next, we import the four previously mentioned components from the react-transition-group package in the Home.js file.

import {Transition, CSSTransition, SwitchTransition, TransitionGroup} from "react-transition-group";

Next, we will understand how each component works.

ConversionComponent

Transition Components provide an API for defining the transition of a component from one state to another during installation and uninstallation.

Now, in the Home component, wrap the h2 tag in the Transition component and update the code like this.

import React, { useState } from "react";

const duration = 300;

const defaultStyle = {
  transition: `opacity ${duration}ms ease-in-out`,
  opacity: 0,
};

const transitionStyles = {
  entering: { opacity: 1 },
  entered: { opacity: 1 },
  exiting: { opacity: 0 },
  exited: { opacity: 0 },
};

const Home = () => {
  const [inProp, setInProp] = useState(false);
  return (
    <>
      <div>
        <Transition in={inProp} timeout={300}>
          {(state) => (
            <h2
              style={{
                ...defaultStyle,
                ...transitionStyles[state],
              }}
            >
              {"TutsPlus - Welcome to React Animations"}
            </h2>
          )}
        </Transition>
        <button onClick={() => setInProp(!inProp)}>
          Click to {inProp ? "Exit" : "Enter"}
        </button>
      </div>
    </>
  );
};

export default Home;

Using the Transition tag, we define the part where the animation occurs. We also specify the in property for the transition using the inProp state, which toggles the transition state.

As you noticed, we specified the animation duration using the timeout property in the defaultStyle and Transition components above. This is because this is how React knows when to remove animation classes from an element and when to remove an element from the DOM.

Save the above changes and refresh the page. Once the page loads, you should be able to see animated text within a few seconds.

CSSTransition Component

The CSSTransition component comes in handy when trying to implement CSS-based animations in React components.

Because this component is based on the Transition component, it inherits all props of that component and also uses several classes to define transitions.

To understand how this works, we add the following code to the index.css file as follows:

.react-animations-enter {
  opacity: 0;
}
.react-animations-enter-active {
  opacity: 1;
  transition: opacity 200ms;
}
.react-animations-exit {
  opacity: 1;
}
.react-animations-exit-active {
  opacity: 0;
  transition: opacity 200ms;
}

From *-enter to *-exit-active, each class defines the transition when the component is "enter", "enter", "exit", and " Exit" status.

Then, in Home.js, we wrap the component content into the CSSTransition tag, passing in in and timeout Properties and the classes we defined earlier:

<div>
    <CSSTransition
        in={displayText}
        timeout={300}
        classNames="react-animations"
        unmountOnExit
    >
        <h2>{"TutsPlus - Welcome to CSSTransition"}</h2>
    </CSSTransition>
        <button onClick={() => setDisplayText(!displayText)}>
          Display Text
        </button>
</div>

Please note that the classNames attribute above has a react-animations value that applies to all classes defined.

SwitchTransition Class

As the name suggests, this component is useful when you want to switch rendering between state transitions based on the selected mode (input-output or output-input). It is useful when you want one component to fade out when another component is inserted.

要访问此实用程序的属性,我们还将组件的内容包装在 SwitchTransition 标记中。还需要注意的是,SwitchTransition 应与 TransitionCSSTransition 组件一起使用。

让我们将以下代码添加到 index.css 文件中,如下所示来创建我们的类:

.fade-enter{
   opacity: 0;
}

.fade-exit{
   opacity: 1;
}

.fade-enter-active{
   opacity: 1;
}

.fade-exit-active{
   opacity: 0;
}

.fade-enter-active,
.fade-exit-active{
   transition: opacity 500ms;
}

让我们看看它是如何工作的,从 out-in 模式开始,这是默认模式:

 const [state, setState] = useState(false);
 
   <SwitchTransition>
     <CSSTransition
       key={state ? "Did you Enjoy our Tutorial?" : "Welcome to TutsPlus"}
       addEndListener={(node, done) => node.addEventListener("transitionend", done, false)}
       classNames='fade'
     >
       <button onClick={() => setState(state => !state)}>
         {state ? "Did you Enjoy our Tutorial?" : "Welcome to TutsPlus"}
       </button>
     </CSSTransition>
   </SwitchTransition>

上面代码中的 key 属性会跟踪组件中的状态,而 addEndListener 属性会阻止组件几乎立即翻转。如果没有它,看起来就像没有实现动画一样。

接下来是输入输出模式,其中 SwitchTransition 标记采用 mode 属性以及 in-out 值。现在更新您的代码以查看其工作原理:

<SwitchTransition mode={"in-out"}>
    {Code goes here}
</SwitchTransition>

过渡组

该组件有助于管理列表中的 TransitionCSSTransition 组件。以下是如何应用它的示例。

像这样更新Home.js

const [items, setItems] = useState(["Manal"]);

const CONTACTS = ["Jane", "Fred", "John", "Doe", "Brown"];

const onAddContacts = () => {
    const newItem = CONTACTS.find((item) => !items.includes(item));
    
    if (newItem) {
      setItems((prev) => [...prev, newItem]);
    }
};

<div>
      <TransitionGroup>
        <h2>Contacts</h2>
        {items.map((item, index) => (
          <CSSTransition key={index} timeout={900} classNames="fade">
            <p>{item}</p>
          </CSSTransition>
        ))}
        <button onClick={onAddContacts}>Add a Contact</button>
      </TransitionGroup>
    </div>

保存以上内容并刷新页面。单击该按钮,该项目应添加到带有动画的列表中。

从上面的代码中,我们初始化了一个名为 CONTACTS 的静态 data 集。然后,定义了一个 onAddContacts 函数,该函数将处理添加新联系人的操作,并在按钮上触发。

列表中的每个项目都包含在 CSSTransition 标记中,以对新插入的项目进行动画处理。最后,该组件被包装在 TransitionGroup 组件中以管理其中包含的转换。

这是完整的 Home.js 组件:

import React, { useState } from "react";

import {
  Transition,
  CSSTransition,
  SwitchTransition,
  TransitionGroup
} from "react-transition-group";

const duration = 300;

const defaultStyle = {
  transition: `opacity ${duration}ms ease-in-out`,
  opacity: 0,
};

const transitionStyles = {
  entering: { opacity: 1 },
  entered: { opacity: 1 },
  exiting: { opacity: 0 },
  exited: { opacity: 0 },
};

const Home = () => {
  const [inProp, setInProp] = useState(false);
  const [displayText, setDisplayText] = useState(false);
  const [state, setState] = useState(false);

  const [items, setItems] = useState(["Manal"]);

  const CONTACTS = ["Jane", "Fred", "John", "Doe", "Brown"];

  const onAddContacts = () => {
    const newItem = CONTACTS.find((item) => !items.includes(item));
    if (newItem) {
      setItems((prev) => [...prev, newItem]);
    }
  };

  return (
    <>
      <div>
        <Transition in={inProp} timeout={300}>
          {(state) => (
            <h2
              style={{
                ...defaultStyle,
                ...transitionStyles[state],
              }}
            >
              {"TutsPlus - Welcome to React Animations"}
            </h2>
          )}
        </Transition>
        <button onClick={() => setInProp(!inProp)}>
          Click to {inProp ? "Exit" : "Enter"}
        </button>
      </div>

      <div>
        <CSSTransition
          in={displayText}
          timeout={300}
          classNames="react-animations"
          unmountOnExit
        >
          <h2>{"TutsPlus - Welcome to CSSTransition"}</h2>
        </CSSTransition>
        <button onClick={() => setDisplayText(!displayText)}>
          Display Text
        </button>
      </div>

      <div>
        <SwitchTransition mode={"in-out"}>
          <CSSTransition
            key={state ? "Did you Enjoy our Tutorial?" : "Welcome to TutsPlus"}
            addEndListener={(node, done) =>
              node.addEventListener("transitionend", done, false)
            }
            classNames="fade"
          >
            <button onClick={() => setState((state) => !state)}>
              {state ? "Did you Enjoy our Tutorial?" : "Welcome to TutsPlus"}
            </button>
          </CSSTransition>
        </SwitchTransition>
      </div>

      <div>
      <TransitionGroup>
        <h2>Contacts</h2>
        {items.map((item, index) => (
          <CSSTransition key={index} timeout={900} classNames="fade">
            <p>{item}</p>
          </CSSTransition>
        ))}
        <button onClick={onAddContacts}>Add a Contact</button>
      </TransitionGroup>
    </div>
    </>
  );
};

export default Home;

总结

在本教程中,您了解了如何开始在 React 中使用动画。您创建了一个简单的 React 应用程序,并了解了如何实现四个 React Transition Group 组件。有关 React 动画的深入信息,我建议阅读官方文档。

本教程的源代码可在 GitHub 上获取。

The above is the detailed content of Explore the world of React animation: an introduction. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn