【发布时间】:2018-04-05 05:10:00
【问题描述】:
完整代码:
https://codesandbox.io/s/j4r7yoollw
我在按钮单击时为模态设置动画。但是当我关闭它时,我希望能够在components/Modal/index.css 中反转动画。我实现了setTimeout 让模态时间淡出,但它不起作用。我该怎么做才能让它发挥作用?
模态/index.js:
import React from 'react';
import Question from './Question';
import Loading from './Loading';
import Success from './Success';
import './index.css';
class Modal extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: false,
success: false,
reverse: false,
};
}
removeUser = () => {
this.setState({ loading: true });
// simulate async loading action
setTimeout(
() =>
this.setState({
loading: false,
success: true,
}),
2000,
);
//simulate promise (function above then this below)
setTimeout(() => this.props.removeUser(this.props.data), 2001);
};
closeModal = () => {
this.setState({ reverse: true });
setTimeout(() => {
this.props.closeModal();
this.setState({
reverse: false,
success: false,
});
}, 3000);
};
render() {
const { id, name } = this.props.data;
const { loading, success } = this.state;
// The gray background
const backdropStyle = {
position: 'fixed',
top: 0,
bottom: 0,
left: 0,
right: 0,
backgroundColor: 'rgba(0,0,0,0.3)',
padding: 50,
};
// The modal "window"
const modalStyle = {
backgroundColor: '#fff',
textAlign: 'center',
borderRadius: 3,
maxWidth: 360,
minHeight: 130,
margin: '0 auto',
};
if (this.props.displayModal) {
return (
<div className={'backdrop ' + (this.state.reverse ? 'reverse' : '')} style={backdropStyle}>
<div className={'modal ' + (this.state.reverse ? 'reverse' : '')} style={modalStyle}>
{!loading &&
!success && (
<Question
id={id}
name={name}
removeUser={this.removeUser}
closeModal={this.closeModal}
/>
)}
{loading && !success && <Loading />}
{!loading && success && <Success closeModal={this.closeModal} />}
</div>
</div>
);
}
return null;
}
}
export default Modal;
模态/index.css:
@keyframes modalFade {
from {
transform: translateY(-50%);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
.modal {
animation-name: modalFade;
animation-duration: 0.3s;
}
@keyframes backdropFade {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.backdrop {
animation-name: backdropFade;
animation-duration: 0.3s;
}
.reverse {
animation-direction: reverse;
}
【问题讨论】:
-
请提供问题内的代码
-
@artgb 完成,codesandbox 中的完整代码
-
刚刚在 Devtools 中注意到“reverse”被添加到 className,所以我想知道是不是 CSS 需要工作?我也在学习。
-
@anand 是的,我认为当我使用
animation-direction: reverse添加类时,css 动画不会再次启动
标签: javascript css reactjs animation frontend