React Transition Group -如何在组件更新时触发动画?



我似乎对React Transition Group的工作原理缺乏基本的理解。在这个简单的示例中,我希望组件在每次更新时淡入。但事实并非如此。为什么会这样呢?如果我切换in prop for,那么它就可以工作了。

import React from 'react';
import ReactDOM from 'react-dom';
import { Container, Button, Alert } from 'react-bootstrap';
import { CSSTransition } from 'react-transition-group';
import './styles.css';
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
rerender: false,
};
this.toggle = this.toggle.bind(this);
}
toggle() {
this.setState((state) => ({
rerender: !state.rerender,
}));
}
componentDidMount() {
console.log('Mounted');
}
componentDidUpdate() {
console.log('Updated');
}
render() {
return (
<div>
<Button onClick={this.toggle}>Click</Button>
<CSSTransition
classNames="fade"
in = {true}
timeout={1000}
>
{this.state.rerender ?  <p> Render On </p> : <p>Render Off</p>}
</CSSTransition>
</div>
);
}
}
ReactDOM.render(
<Example />,
document.getElementById('root')
);

CSS

.fade-enter {
opacity: 1;
}
.fade-enter-active {
opacity: 0;
transition-property: opacity;
transition-duration: 1000ms;
}
.fade-enter-done {
opacity: 0;
}

从我的路线阅读,我认为离开"in"prop为true时,每次组件更新时都会应用enter-* CSS类。正如您所看到的,当我按下按钮时,因此更新了组件。没有动画发生:https://codesandbox.io/s/beautiful-brahmagupta-6nmze?file=/index.js另一方面,如果我将in道具设置为true和false,那么输入类将被应用。在代码沙箱中尝试一下,然后自己看看。

...
<CSSTransition
classNames="fade"
in = {this.state.rerender}
timeout={1000}
>
...

据我所知,React过渡组只在过渡阶段工作,所以在prop中应该是

  • falsetotrue
  • truefalse

你可以在源代码中清楚地看到

_proto.componentDidUpdate = function componentDidUpdate(prevProps) {
var nextStatus = null;
if (prevProps !== this.props) {
var status = this.state.status;
if (this.props.in) {
if (status !== ENTERING && status !== ENTERED) {
nextStatus = ENTERING;
}
} else {
if (status === ENTERING || status === ENTERED) {
nextStatus = EXITING;
}
}
}
this.updateStatus(false, nextStatus);
};
_proto.updateStatus = function updateStatus(mounting, nextStatus) {
if (mounting === void 0) {
mounting = false;
}
if (nextStatus !== null) {
// nextStatus will always be ENTERING or EXITING.
this.cancelNextCallback();
if (nextStatus === ENTERING) {
this.performEnter(mounting);
} else {
this.performExit();
}
} else if (this.props.unmountOnExit && this.state.status === EXITED) {
this.setState({
status: UNMOUNTED
});
}
};

所以如果props没有改变什么也不会发生

在你的情况下,你试图只应用进入-*类:你可以让in = {this.state.rerender}和提供进入-*类在css文件中没有退出-*

也可以使用另一个库在安装时为组件动画,如:

最新更新