ReactCSSTransitionGroup componentWillLeave未被调用

时间:2016-03-04 18:22:31

标签: javascript reactjs ecmascript-6 transition

我试图玩ReactCssTransition但不知何故该事件未被调用(componentWillLeave)

这是我的组件

import React, { Component } from 'react'
import TransitionGroup from 'react-addons-css-transition-group'

export default class TransitionComponent extends Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (
      let {componentKey} = this.props
      <TransitionGroup transitionName="example" transitionEnterTimeout={500} transitionLeaveTimeout={500}>
        <Item key={"item"+componentKey} />
      </TransitionGroup>
    );
  }
}

和子组件

class Item extends Component {

  componentDidEnter() {
    console.log("component did enter");
  }

  componentWillLeave(callback) {
    console.log("component will leave");
  }

  render() {
    return (
      <div>Item</div>
    )
  }
}

有任何线索吗?谢谢!

2 个答案:

答案 0 :(得分:4)

由于未在“componentWillEnter”函数中调用回调而导致类似问题。引自React documentation

  

它将阻止其他动画发生,直到调用回调为止

class Item extends Component {

    componentWillEnter(callback) {
        console.log("component will enter");
        callback();
    }

    componentDidEnter() {
        console.log("component did enter");
    }

    componentWillLeave(callback) {
        console.log("component will leave");
        callback();
    }

    render() {
        return (
            <div>Item</div>
        )
    }
}

答案 1 :(得分:-2)

请原谅我,因为我是React的新手,但我的理解是,当安装/卸载组件时,你将无法获得componentDidEnter()和componentWillLeave()生命周期钩子。

您可以随意使用componentDidMount()和componentWillUnmount()。

所以用这个替换上面的部分你应该看到你的控制台日志:

  componentDidMount() {
    console.log('Component did mount');
  }

  componentWillUnmount() {
    console.log('Component will unmount');
  }

我相信如果你想要访问所有需要使用ReactTransitionGroup的生命周期钩子,我还没想出如何实现它。

虽然作者解释得很好,但仍有一个good article on it on Medium

文章中有一点她谈到用ReactTransitionGroup组件包装她的子组件,我相信这就是你要找的东西。基本上将它包裹在您当前的<Item /> ...

周围