Reactjs在不使用插件的情况下为离开组件设置动画

Reactjs animate a leaving component without using addon

本文关键字:离开 组件 设置 动画 情况下 插件 Reactjs      更新时间:2023-09-26

在react.js中,我知道可以使用插件ReactCSSTransitionGroup执行动画。作为学习过程的一部分,我正在尝试编写"vanilla-js"来在进入和离开时为组件设置动画。

当进入时安装子组件时,我想出了一些简单的代码如下

class Child extends React.Component {
  constructor(props) {
    super(props)
    this.state = { opacity: 0 }
  }
  componentDidMount() {
    this.setState({ opacity: 1 }) // change the opacity when the component is mounted
  }
  render() {
    <div style={{ transition: 'opacity 0.3s', opacity: this.state.opacity }}>
      I am a child component
    </div>
  }
}
class Parent extends React.Component {
  render() {
    return this.props.someProp === true ? <Child /> : null
  }
}

然而,我正在为如何在离开时为组件设置动画而苦苦挣扎。componentWillUnmount无法与this.setState({ opacity: 0 })一起使用,因为该组件将被删除。我试过阅读ReactCSSTransitionGroup中的源代码,但似乎没有领会要点。有人能提供一个简单的示例代码来解释离职组件应该如何实现吗?

问题是,您无法从组件本身中真正处理此问题。这就是为什么您只能在ReactCSSTransitionGroup组件的子级上使用React转换。这是使用ReactTransitionGroup元素添加的新生命周期方法来处理的,如文档中所述。

重要的方法是componentWillLeave(callback),它在调用回调之前不会从DOM中删除元素。因此,如果你想自己实现类似的行为,你需要采取类似的方法,创建一些包装组件,它可以处理它的子生命周期,并可能扩展它