Table of Contents
Animation in React
start using
React Transition Group Settings
ConversionComponent
CSSTransition Component
SwitchTransition Class
过渡组
总结
Home CMS Tutorial WordPress Explore the world of React animation: an introduction

Explore the world of React animation: an introduction

Sep 03, 2023 pm 12:25 PM

探索 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
Copy after login

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

<title>TutsPlus - React Animations</title>
Copy after login

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;
Copy after login

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;
Copy after login

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

npm run start
Copy after login

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
Copy after login

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";
Copy after login

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;
Copy after login

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;
}
Copy after login

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>
Copy after login

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;
}
Copy after login

让我们看看它是如何工作的,从 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>
Copy after login

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

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

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

过渡组

该组件有助于管理列表中的 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>
Copy after login

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

从上面的代码中,我们初始化了一个名为 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;
Copy after login

总结

在本教程中,您了解了如何开始在 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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is WordPress easy for beginners? Is WordPress easy for beginners? Apr 03, 2025 am 12:02 AM

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

Can I learn WordPress in 3 days? Can I learn WordPress in 3 days? Apr 09, 2025 am 12:16 AM

Can learn WordPress within three days. 1. Master basic knowledge, such as themes, plug-ins, etc. 2. Understand the core functions, including installation and working principles. 3. Learn basic and advanced usage through examples. 4. Understand debugging techniques and performance optimization suggestions.

What is the WordPress good for? What is the WordPress good for? Apr 07, 2025 am 12:06 AM

WordPressisgoodforvirtuallyanywebprojectduetoitsversatilityasaCMS.Itexcelsin:1)user-friendliness,allowingeasywebsitesetup;2)flexibilityandcustomizationwithnumerousthemesandplugins;3)SEOoptimization;and4)strongcommunitysupport,thoughusersmustmanageper

Should I use Wix or WordPress? Should I use Wix or WordPress? Apr 06, 2025 am 12:11 AM

Wix is ​​suitable for users who have no programming experience, and WordPress is suitable for users who want more control and expansion capabilities. 1) Wix provides drag-and-drop editors and rich templates, making it easy to quickly build a website. 2) As an open source CMS, WordPress has a huge community and plug-in ecosystem, supporting in-depth customization and expansion.

How much does WordPress cost? How much does WordPress cost? Apr 05, 2025 am 12:13 AM

WordPress itself is free, but it costs extra to use: 1. WordPress.com offers a package ranging from free to paid, with prices ranging from a few dollars per month to dozens of dollars; 2. WordPress.org requires purchasing a domain name (10-20 US dollars per year) and hosting services (5-50 US dollars per month); 3. Most plug-ins and themes are free, and the paid price ranges from tens to hundreds of dollars; by choosing the right hosting service, using plug-ins and themes reasonably, and regularly maintaining and optimizing, the cost of WordPress can be effectively controlled and optimized.

Is WordPress a CMS? Is WordPress a CMS? Apr 08, 2025 am 12:02 AM

WordPress is a Content Management System (CMS). It provides content management, user management, themes and plug-in capabilities to support the creation and management of website content. Its working principle includes database management, template systems and plug-in architecture, suitable for a variety of needs from blogs to corporate websites.

Why would anyone use WordPress? Why would anyone use WordPress? Apr 02, 2025 pm 02:57 PM

People choose to use WordPress because of its power and flexibility. 1) WordPress is an open source CMS with strong ease of use and scalability, suitable for various website needs. 2) It has rich themes and plugins, a huge ecosystem and strong community support. 3) The working principle of WordPress is based on themes, plug-ins and core functions, and uses PHP and MySQL to process data, and supports performance optimization.

Is WordPress still free? Is WordPress still free? Apr 04, 2025 am 12:06 AM

The core version of WordPress is free, but other fees may be incurred during use. 1. Domain names and hosting services require payment. 2. Advanced themes and plug-ins may be charged. 3. Professional services and advanced features may be charged.

See all articles