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)

不言
Release: 2018-07-07 17:52:14
Original
3301 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template