react 官网动画库(react-transition-group)的新写法

一、react-transition-group 一个官网供应的动画过分库。

搜刮了网上关于react动画的,许多的答案都是很久之前的了老版本了,而如今官方供应的是叫react-transition-group 它是之前两个的合体版本,所以写下这个纪录一下,同时也给一些须要的猿门给一些小的提醒。
1、装置

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

# yarn
yarn add react-transition-group

而官方供应的三个组建Transition,CSSTransition,TransitonGroup

Transition

过渡组件(Transiton)许可您用一个简朴的声明性API形貌跟着时刻的推移从一个组件状况到另一个组件状况的转换。最经常使用的是用来动画一个组件的装置和卸载,但也能够用来形貌在恰当的过渡状况。默许状况下,该组件不会变动其显现的组件的行动,它只跟踪组件的“进入”和“退出”的状况。由你来为这些状况定义结果。(翻译)
现实的状况就是你假如只写这个组件是没有任何的结果的,就和你写一个div一样。所以你须要给他们给予一些参数才能够。比方下面这个例子

//本身简朴的封装了一个,该有的参数都由了,能够自行粘贴在本身的代码内里去尝尝。
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(
              <div style={{
                ...defaultStyle,
                ...transitionStyles[state]
              }}>
                {this.props.children}
              </div>
            )
          }
        }
      </Transition>
    );
  }
}

个中上面的状况有四种:

entering
entered
exiting
exited

组件的初始化状况都停留在exited
上面就是写的一个最基本的例子,下面是怎样的挪用

let num = 1;
class Dnd extends React.Component {
  state = {
    ins: true,
    current: 1,
    dom: <div className={l.test}>
            ceshi weizhi {num}
          </div>
  }
  handle = (bool) => {
    this.setState({
      test: !bool
    })
  }
  end = () => {
    const that = this;
    num = num + 1;
    setTimeout(function () {
      that.setState({
        test: true,
        dom: <div className={l.test}>
              888888 {num}
            </div>
      }) 
    }, 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>
    )
  }
}
// 结果是每次点击按钮都邑举行一次进场和进场的动画。也能够自行衍生。
这个组件也许就是如许的,如许适合写一个tab范例的页面,在切换的时刻能够展现差别的dom

CSSTransition

此组件是在转换的涌现、进入、退出阶段运用一对类名(也就是className),靠这个来激活CSS动画。所以参数和日常平凡的className差别,参数为:classNames
参数:(重要)in, timeout, unmountOnExit, classNames, 用法同Transition。看以下例子:

state  = {
    star: false
}


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

结果是点击button 显现星星,在点击消逝星星的动画!
参数classNames="star", 组件会找对应状况的className, 以下

.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;
  }

顺次实行的递次是

1、星星显现 对应的class为star-enter star-enter-active 动画走完为star-enter-done
2、星星消逝 对应的class为star-exit  star-exit-active 动画走完为star-exit-done

假如根据官网的诠释就是以下, 有兴致的能够自行去试一试。

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,
}}

每一个阶段的钩子函数同Transition.

TransitionGroup

一看group就晓得肯定是列表形状的动画了!然则看了官网后晓得,TransitionGroup不供应任何情势的动画,详细的动画取决与你包裹的Transition || CSSTransition的动画,所以你能够在列表内里做出差别范例的动画出来。下面来看一个例子

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 (
      <div>
        <TransitionGroup className="todo-list">
          {items.map(({ id, text }) => (
            <CSSTransition
              key={id}
              timeout={500}
              classNames="fade"
            >
              <div>
                <Button
                  onClick={() => {
                    this.setState(state => ({
                      items: state.items.filter(
                        item => item.id !== id
                      ),
                    }));
                  }}
                >
                  &times;
                </Button>
                {text}
              </div>
            </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>
      </div>
    );
  }
}

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;
  }

结果是增添和删除列表项中的一个,发生渐入渐失的结果!说白了也就是多个Transition 或许CSSTransition组合的结果。
然则也供应一些参数

1、component  default 'div' 也就是TransitionGroup衬着出来的标签为div,也能够就行变动,比方component="span" 衬着出来的就是span标签了
2、children 相当于你给的组件,能够是字符串或许自定义组件等。
3、appear  写在TransitionGroup内里相当于开启或许制止内里的Transition || CSSTransition 轻易写的作用

三个组件也许的特征就是这些。剩下的端赖本身去开发了!后续会录入一些小的例子来解说,敬请期待。。。。

    原文作者:JeremyChen
    原文地址: https://segmentfault.com/a/1190000015487495
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞