使用 VelocityJS 响应动画

React Animations with VelocityJS

我真的很难让动画在 React 中工作。也许我从根本上缺少一些东西。

我在 coffeescript 中这样做 -- 希望你不介意。

我创建了一个非常简单的 UI。有一个 div 里面有一个标题。单击标题时,标题会更改,我想使用 VelocityJS 为淡入淡出 in/out 过渡设置动画。

ReactTransitionGroup = React.createFactory(React.addons.CSSTransitionGroup)

{div} = React.DOM

TitleClass = React.createClass
  displayName: "Title"
  render: ->
    (div {onClick:@props.changeTitle}, @props.title)

  componentWillEnter: (done) ->
    node = @getDOMNode()
    console.log "willEnter"
    Velocity(node, 'transition.fadeIn', {complete: done})

  componentWillLeave: (done) ->
    node = @getDOMNode()
    console.log "willLeave"
    Velocity(node, 'transition.fadeOut', {complete: done})


Title = React.createFactory(TitleClass)

MainClass = React.createClass
  displayName: "Main"
  getInitialState: ->
    title: 'Main'
  changeTitle: ->
    if @state.title is 'Home'
      @setState {title: 'Main'}
    else
      @setState {title: 'Home'}
  render: ->
    (div {style:{width: '100%', fontSize:'25px', textAlign:'center', marginTop:'20px'}},
      (ReactTransitionGroup {transitionName: 'fade'},
        (Title {changeTitle:@changeTitle, title:@state.title})
      )
    )

Main = React.createFactory(MainClass)

React.render(Main({}), document.body)

就是这样。非常自我解释。这个ReactTransitionGroup对我来说还是个谜。据我了解,它的任何 children 都应该调用 componentWillEntercomponentWillLeave 但这并没有最终发生。 According to the docs 似乎我应该看到 console.log "willEnter" 但我没有。

我已经挂断这个几个小时了。有什么想法吗?

CSSTransitionGroup 监视写入元素的 CSS transition 属性 的实际使用。我不确定具体如何,但听起来 Velocity 并没有以 CSSTransitionGroup 想要的方式工作。您可能需要手动调用 componentWillEntercomponentWillLeave。在这种情况下,听起来并不难。

编辑: 哎呀,我错过了您在组中的 child 组件上没有 key 属性。据我所知,如果你拿到那些孩子的钥匙,componentWillEntercomponentWillLeave 应该被调用,不管其他什么。

我在上面的代码中发现了两个问题。

第一个是您使用的是 React.addons.CSSTransitionGroup 而不是 React.addons.TransitionGroup

第二个问题是您期望 componentWillEnter 在装载时被触发,而实际上 componentWillAppear 是被触发的方法。

最终的解决方案是使用 React.addons.TransitionGroupCSSTransitionGroup 只是一个可以做 CSS 事情的包装器。

另一个问题是要获得动画回调,children必须有一个键!

ReactTransitionGroup = React.createFactory(React.addons.TransitionGroup)

# {clip}

(ReactTransitionGroup {transitionName: 'fade'},
  (Title {changeTitle:@changeTitle, title:@state.title, key:'title'})
)