gpt4 book ai didi

javascript - 使用 React 和 react-transition-group 卸载动画

转载 作者:行者123 更新时间:2023-11-29 16:01:59 25 4
gpt4 key购买 nike

我正在使用 React,我正在尝试使用 React-transition-group 创建一个 Fade 组件,以根据状态中存储的条件淡入和淡出元素:http://reactcommunity.org/react-transition-group/css-transition/

这是我现在拥有的:

import React from "react";
import ReactDOM from "react-dom";
import { CSSTransition } from "react-transition-group";

import "./styles.css";

class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
mounted: false
};
}
componentDidMount() {
setTimeout(() => {
this.setState({
mounted: true
});
}, 10);
}
render() {
return (
<div className="root">
<CSSTransition
in={this.state.mounted}
appear={true}
unmountOnExit
classNames="fade"
timeout={1000}
>
{this.state.mounted ? (
<div>
<button
onClick={() => {
this.setState({
mounted: !this.state.mounted
});
}}
>
Remove
</button>
<div>COMPONENT</div>
</div>
) : (
<div />
)}
</CSSTransition>
</div>
);
}
}

这是CSS

.fade-enter {
opacity: 0;
transition: opacity .5s ease;
}

.fade-enter-active {
opacity: 1;
transition: opacity .5s ease;
}

.fade-exit {
opacity: 1;
transition: opacity .5s ease;
}

.fade-exit-active {
opacity: 0;
transition: opacity .5s ease;
}

安装组件时,不透明度会从 0 过渡到 1,耗时 0.5 秒。但是当它卸载时,它不是动画的:组件在没有过渡的情况下消失。

我用这个组件制作了一个沙箱来测试它:https://codesandbox.io/s/k027m33y23我确信这是一个常见的情况,但我找不到在卸载时为组件设置动画的方法。如果有人有任何想法,我们将非常欢迎!

-- 编辑--正如@IPutuYogaPermana 所说,CSSTransition 中的条件渲染不是必需的。所以这个:

{this.state.mounted ? (
<div>
<button
onClick={() => {
this.setState({
mounted: !this.state.mounted
});
}}
>
Remove
</button>
<div>COMPONENT</div>
</div>
) : (
<div />
)}

应该是这样的:

<div>
<button
onClick={() => {
this.setState({
mounted: !this.state.mounted
});
}}
>
Remove
</button>
<div>COMPONENT</div>
</div>

组件将根据 CSSTransition 组件中的 in 属性自动挂载或卸载。这是 codesandbox 中的最终代码:https://codesandbox.io/s/62m86nm7qw

最佳答案

这是意料之中的,因为随着状态的改变,动画还没有开始,但是 children 已经走了。

所以它就像神奇地瞬间消失。那么我们只需要隐藏它对吗?删除条件渲染。

我检查过,节点在动画完成后自动移除。所以不需要使用条件渲染。幸运的是!代码变为:

import React from "react";
import ReactDOM from "react-dom";
import { CSSTransition } from "react-transition-group";

import "./styles.css";

class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
logoIntro: true,
mounted: false
};
}
componentDidMount() {
this.setState({
mounted: true
});
}
render() {
return (
<div className="root">
<CSSTransition
in={this.state.mounted}
appear={true}
unmountOnExit
classNames="fade"
timeout={1000}
>
<div>
<button
onClick={() => {
this.setState({
mounted: !this.state.mounted
});
}}
>
Remove
</button>
<div>SOME COMPONENT</div>
</div>
</CSSTransition>
</div>
);
}
}

ReactDOM.render(<Example />, document.getElementById("root"));

关于javascript - 使用 React 和 react-transition-group 卸载动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51770658/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com