反应动画不起作用

时间:2015-04-26 23:26:47

标签: javascript reactjs

我有一个Notification类来管理从UI创建/删除通知。我可以成功显示/隐藏通知,但通知不会动画显示/输出。

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>
    )

  }

}

2 个答案:

答案 0 :(得分:5)

ReactCSSTransitionGroup只会在其子项props中添加或删除时为其子项设置动画。在您的情况下,children的{​​{1}}道具永远不会改变。

以下是您可以做的一个例子:

ReactCSSTransitionGroup

每次添加或删除通知时,都会在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> ) } } 的{​​{1}}道具中添加或删除其相应的元素,然后可以将其设置为正确的动画。

答案 1 :(得分:2)

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

默认情况下已停用:https://github.com/facebook/react/blob/master/src/addons/transitions/ReactCSSTransitionGroup.js#L38