Table of Contents
一, react-transition-group is an animation transition library provided by the official website.
Transition
CSSTransition
TransitionGroup
Home Web Front-end JS Tutorial New writing method of react official website animation library (react-transition-group)

New writing method of react official website animation library (react-transition-group)

Jul 07, 2018 pm 05:52 PM
javascript react.js

This article mainly introduces the new way of writing the react official website animation library (react-transition-group), which has a certain reference value. Now I share it with you. Friends in need can refer to it

一, react-transition-group is an animation transition library provided by the official website.

I searched the Internet about react animation. Many of the answers are old versions from a long time ago, and now the official one is called react-transition-group It is the previous two The combined version, so I wrote this down to record it, and also gave some tips to those who need it.
1. Install

# npm
npm install react-transition-group --save

# yarn
yarn add react-transition-group
Copy after login

and the three officially provided components Transition, CSSTransition, TransitonGroup.

Transition

Transition components (Transiton) allow you to describe the transition from one component state to another over time with a simple declarative API. Most commonly used to animate the installation and uninstallation of a component, but can also be used to describe transition states where appropriate. By default, this component does not change the behavior of the component it renders, it only tracks the "entering" and "exiting" states of the component. It's up to you to define the effects for these states. (Translation)
The actual situation is that if you only write this component, it will have no effect, just like if you write a p. So you need to give them some parameters. For example, the following example

//自己简单的封装了一个,该有的参数都由了,可以自行粘贴在自己的代码里面去试试。
class Fade extends React.Component {
  constructor(props) {
    super(props);
  }
  done =() => {
    // console.log('结束了')
  }
  addaddEndListener = (node) => { //原生时间transition运动的事件
    node.addEventListener('transitionend', this.done, false);
  }

  // 三个进入状态的事件,可以做你想做的事情
  onEnter = (node, isAppearing) => {
    console.log(isAppearing, 'onEnter')
  }
  onEntering = (node, isAppearing) => {
    console.log(isAppearing, 'onEntering')
  }
  onEntered = (node, isAppearing) => {
    console.log(isAppearing, 'onEntered')
  }

  // 三个退出的状态的事件
  onExit = (node) => {
    console.log('onExit')
  }
  onExiting = () => {
    console.log('onExiting')
  }
  onExited = () => {
    console.log('onExited')
    this.props.self()
  }
  render() {
    const { in: inProp, dur} = this.props;
    const defaultStyle = {
      transition: `transform ${300}ms ease-in-out, opacity ${300}ms ease-in-out`,
      transform: 'translateX(100px)',
      opacity: '0'
    }

    const transitionStyles = {
      entering: { transform: 'translateX(100px)', opacity: '0'},
      entered:  { transform: 'translateX(0px)', opacity: '1' },
      exiting: {transform: 'translateX(0px)', opacity: '1'},
      exited: {transform: 'translateX(0px)', opacity: '0'}
    };
    const duration = {
      enter: 300,
      exit: 300,
    }
    // 上面的都是基本参数,样式的转变以及时间的设定,具体的可以看官网文档
    // 样式也可以写成className 例如<MyComponent className={`fade fade-${status}`} />
    return (
      <Transition 
        onEnter={this.onEnter}
        onEntering={this.onEntering}
        onEntered={this.onEntered}

        onExit={this.onExit}
        onExiting={this.onExiting}
        onExited={this.onExited}

        addEndListener={this.addaddEndListener} 
        in={inProp} 
        unmountOnExit={false} // 为true 代表退出的时候移除dom
        appear={true} // 为true  渲染的时候就直接执行动画,默认false,
        timeout={duration}
      >
        {
          state => {
            console.log(state, '###') //你可以很直观的看到组件加载和卸载时候的状态
            return(
              <p style={{
                ...defaultStyle,
                ...transitionStyles[state]
              }}>
                {this.props.children}
              </p>
            )
          }
        }
      </Transition>
    );
  }
}
Copy after login

There are four states above:

entering
entered
exiting
exited
Copy after login

The initialization state of the component stays at exited
The above is the most basic one written Example, the following is how to call

let num = 1;
class Dnd extends React.Component {
  state = {
    ins: true,
    current: 1,
    dom: <p className={l.test}>
            ceshi weizhi {num}
          </p>
  }
  handle = (bool) => {
    this.setState({
      test: !bool
    })
  }
  end = () => {
    const that = this;
    num = num + 1;
    setTimeout(function () {
      that.setState({
        test: true,
        dom: <p className={l.test}>
              888888 {num}
            </p>
      }) 
    }, 500)
    
  }
  render () {
    const { location } = this.props
    const { test } = this.state;
    return (
      <MainLayout location={location}>
        <Button onClick={this.handle.bind(null, this.state.test)}>点击transition</Button>
        <Fade in={this.state.test} self={this.end}>
          {this.state.dom}
        </Fade>
      </MainLayout>
    )
  }
}
// 效果是每次点击按钮都会进行一次进场和出场的动画。也可以自行衍生。
Copy after login
这个组件大概就是这样的,这样适合写一个tab类型的页面,在切换的时候可以展示不同的dom
Copy after login

CSSTransition

This component applies a pair of class names (that is, className) in the emergence, entry, and exit phases of the transition, and relies on this to activate CSS animation. Therefore, the parameters are different from the usual className. The parameters are: classNames
Parameters: (mainly) in, timeout, unmountOnExit, classNames, the usage is the same as Transition. Look at the following example:

state  = {
    star: false
}


<Button onClick={this.handleStar.bind(null, star)}>start</Button>
<CSSTransition
  in={star}
  timeout={300}
  classNames="star"
  unmountOnExit
>
  <p className="star">⭐</p>
</CSSTransition>
Copy after login

The effect is to click the button to display the stars, and click the animation of the stars to disappear!
ParametersclassNames="star", the component will find the className of the corresponding state, as follows

.star {
    display: inline-block;
    margin-left: 0.5rem;
    transform: scale(1.25);
  }
  .star-enter {
    opacity: 0.01;
    transform: translateY(-100%) scale(0.75);
  }
  .star-enter-active {
    opacity: 1;
    transform: translateY(0%) scale(1.25);
    transition: all 300ms ease-out;
  }
  .star-exit {
    opacity: 1;
    transform: scale(1.25);
  }
  .star-exit-active {
    opacity: 0;
    transform: scale(4);
    transition: all 300ms ease-in;
  }
Copy after login

The order of execution is

1、星星显示 对应的class为star-enter star-enter-active 动画走完为star-enter-done
2、星星消失 对应的class为star-exit  star-exit-active 动画走完为star-exit-done
Copy after login

If you follow the explanation on the official website, it is As follows, if you are interested, you can try it yourself.

classNames={{
 appear: 'my-appear',
 appearActive: 'my-active-appear',
 enter: 'my-enter',
 enterActive: 'my-active-enter',
 enterDone: 'my-done-enter,
 exit: 'my-exit',
 exitActive: 'my-active-exit',
 exitDone: 'my-done-exit,
}}
Copy after login

The hook function of each stage is the same as Transition.

TransitionGroup

As soon as you look at the group, you will know that it must be a list-shaped animation! But after reading the official website, I learned that TransitionGroup does not provide any form of animation. The specific animation depends on the animation of the Transition || CSSTransition you wrapped, so you can make different types of animations in the list. Let’s take a look at an example

class List extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [
        { id: 1, text: 'Buy eggs' },
        { id: 2, text: 'Pay bills' },
        { id: 3, text: 'Invite friends over' },
        { id: 4, text: 'Fix the TV' },
      ]
    }
  }

  render() {
    const { items } = this.state; 
    return (
      <p>
        <TransitionGroup className="todo-list">
          {items.map(({ id, text }) => (
            <CSSTransition
              key={id}
              timeout={500}
              classNames="fade"
            >
              <p>
                <Button
                  onClick={() => {
                    this.setState(state => ({
                      items: state.items.filter(
                        item => item.id !== id
                      ),
                    }));
                  }}
                >
                  &times;
                </Button>
                {text}
              </p>
            </CSSTransition>
          ))}
        </TransitionGroup>
        <Button
          type="button"
          onClick={() => {
            const text = prompt('Enter some text');
            if (text) {
              this.setState(state => ({
                items: [
                  ...state.items,
                  { id: 1123, text },
                ],
              }));
            }
          }}
        >
          Add Item
        </Button>
      </p>
    );
  }
}
Copy after login

css

.fade-enter {
    opacity: 0.01;
  }
  .fade-enter-active {
    opacity: 1;
    transition: opacity 500ms ease-in;
  }
  .fade-exit {
    opacity: 1;
  }
  .fade-exit-active {
    opacity: 0.01;
    transition: opacity 500ms ease-in;
  }
Copy after login

The effect is to add and delete one of the list items, resulting in a fading effect! To put it bluntly, it is the effect of a combination of multiple Transitions or CSSTransitions.
But it also provides some parameters

1、component  default 'p' 也就是TransitionGroup渲染出来的标签为p,也可以就行更改,例如component="span" 渲染出来的就是span标签了
2、children 相当于你给的组件,可以是字符串或者自定义组件等。
3、appear  写在TransitionGroup里面相当于开启或者禁止里面的Transition || CSSTransition 方便写的作用
Copy after login

The approximate characteristics of the three components are these. The rest is all up to you to develop! Some small examples will be included in the follow-up to explain, so stay tuned. . . .

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Native JS encapsulates the vertical scrolling animation tool function based on window.scrollTo()

Jquery adds loading Transition Mask

The above is the detailed content of New writing method of react official website animation library (react-transition-group). 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles