在切换时使用CSSTransitionGroup对动画进行反应

时间:2017-05-04 13:07:58

标签: javascript reactjs reactcsstransitiongroup

当点击按钮在状态之间切换时,我试图在组件进入和离开之间进行转换

我还尝试将<UserDetails /><UserEdit />作为单独的组件,但结果相同,因为没有触发动画。

https://www.webpackbin.com/bins/-KjIPcMeQF3iriHRqTBW

Hello.js

import CSSTransitionGroup from 'react-transition-group/CSSTransitionGroup'
import './styles.css'
export default class Hello extends React.Component {
constructor() {
super()

this.state = { showEdit: false }
this.handleEdit = this.handleEdit.bind(this)
}

handleEdit() { this.setState({ showEdit: !this.state.showEdit }) } 

render() {

 const UserDetails = () => (
 <div className="componenta" key="1">UserDetails</div>
 )
 const UserEdit = () => (
 <div className="componentb" key="2">UserEdit</div>
 )

return(
<div >
    <CSSTransitionGroup 
      transitionName="example"
      transitionEnterTimeout={10}
      transitionLeaveTimeout={600}>
    {this.state.showEdit ? <UserDetails /> : <UserEdit />}
    </CSSTransitionGroup>
    <button onClick={this.handleEdit}>Toggle</button>
</div>
)
}
}

styles.css的

.thing-enter {
 opacity: 0.01;
 transition: opacity 1s ease-in;
}

.thing-enter.thing-enter-active {
  opacity: 1;
}

 .thing-leave {
  opacity: 1;
  transition: opacity 1s ease-in;
 }

 .thing-leave.thing-leave-active {
  opacity: 0.01;
 }

2 个答案:

答案 0 :(得分:1)

您将key属性设置为错误的项目 - <div>不是CSSTransitionGroup的直接后代(因为您通过将其定义为函数将其包装到组件中) ,因此它不知道添加或删除了哪些项目。您必须将密钥设置为UserDetailsUserEdit,因此CSSTransitionGroup可以正确判断其子女的变化。

以下是适用的render方法:

render() {

    const UserDetails = () => (
      <div className="componenta">UserDetails</div>
    )
    const UserEdit = () => (
      <div className="componentb">UserEdit</div>
    )
    return(
    <div >
        <CSSTransitionGroup 
          transitionName="example"
          transitionEnterTimeout={10}
          transitionLeaveTimeout={600}>
        {this.state.showEdit ? <UserDetails key="1" /> : <UserEdit key="2" />}
        </CSSTransitionGroup>
        <button onClick={this.handleEdit}>Toggle</button>
    </div>
    )
  }

另一种方法是将UserDetailsUserEdit存储到变量中,然后将其渲染为变量。这样您就可以将key属性保留在现在的位置,而不是移动它们。

答案 1 :(得分:0)

以下是使用display:none隐藏卸载组件的工作示例

enter link description here