反应动画不起作用

React animation not working

我有一个 Notification class 来管理来自 UI 的 creating/removing 通知。我可以成功 show/hide 通知,但通知没有动画 in/out。

import React from 'react'
import addons from 'react/addons'

const ReactCSSTransitionGroup = React.addons.CSSTransitionGroup

let id = 0
export default class Notification {

  constructor (content, className) {

    let div = document.createElement('div')
    document.body.appendChild(div)

    let onClose = () => React.unmountComponentAtNode(div)

    React.render(
      <NotificationElement className={ className } id={ id++ } onClose={ onClose }>
        { content }
      </NotificationElement>,
      div
    )

  }

}

class NotificationElement extends React.Component {

  constructor(_) {
    super(_)
  }

  render() {

    const className = `Notification ${ this.props.className }`

    return (
      <ReactCSSTransitionGroup transitionName="slideIn">
        <div className={ className } key={ this.props.id }>
          { this.props.children }
          <a className="close-button" onClick={ this.props.onClose }>&times;</a>
        </div>
      </ReactCSSTransitionGroup>
    )

  }

}

ReactCSSTransitionGroup 只会在其子项添加或从其 props 中移除时对其子项进行动画处理。在您的情况下,ReactCSSTransitionGroupchildren 道具永远不会改变。

以下是您可以改为执行的示例:

let notificationsContainer = document.createElement('div');
document.body.appendChild(notificationsContainer);

let notifications = [];
function renderNotifications() {
  React.render(<Notifications notifications={notifications} />, notificationsContainer);
}

class Notifications extends React.Component {

  render() {
    return (
      <ReactCSSTransitionGroup transitionName="slideIn">
        {this.props.notifications.map(notification =>
          <NotificationElement
            key={ notification.id }
            className={ notification.className }
            onClose={ notification.onClose }
            children={ content }
            />
        )}
      </ReactCSSTransitionGroup>
    );
  }

}

let id = 0
export default class Notification {

  constructor (content, className) {

    let notification = {
      id: id++, content, className,
    };

    notification.onClose = () => {
      notifications.splice(notifications.indexOf(notification), 1);
      renderNotifications();
    };

    notifications.push(notification);
    renderNotifications();

  }

}

class NotificationElement extends React.Component {

  constructor(_) {
    super(_)
  }

  render() {

    const className = `Notification ${ this.props.className }`

    return (
      <div className={ className }>
        { this.props.children }
        <a className="close-button" onClick={ this.props.onClose }>&times;</a>
      </div>
    )

  }

}

每次添加或删除通知时,都会从 ReactCSSTransitionGroupchildren 属性中添加或删除相应的元素,然后可以将其适当地动画化。

您可以将 transitionAppear={true} 添加到您的 <ReactCSSTranstionGroup /> 以使其为初始渲染设置动画。

默认禁用:https://github.com/facebook/react/blob/master/src/addons/transitions/ReactCSSTransitionGroup.js#L38