我设置淡入淡出过渡的代码是最简单的:
import React from 'react';
import { Transition } from 'react-transition-group';
import PropTypes from 'prop-types';
const duration = 250;
const defaultStyle = {
transition: `opacity ${duration}ms ease-in-out, color ${duration}ms ease-in-out`,
opacity: 0,
}
const transitionStyles = {
entering: { opacity: 0 },
entered: { opacity: 1 },
exiting: { opacity: 1 },
exited: { opacity: 0 },
};
export default class Fade extends React.Component {
constructor(props) {
super(props);
this.state = {
in: false,
};
}
componentDidMount() {
this.setState({ in: true });
}
componentWillUnmount() {
this.setState({ in: false });
}
render() {
return(
<Transition in={!!this.state.in} timeout={{ enter: 250, exit: 250, }} unmountOnExit={this.props.unmountOnExit || false} >
{(state) => {
return (
<div
className={this.props.classes ? this.props.classes : ''}
style={{ ...defaultStyle, ...transitionStyles[state],}}>
{this.props.children}
</div>
)
}}
</Transition>
)
}
}
Fade.propTypes = {
classes: PropTypes.string,
};
将您的任何组件包裹在其中进行尝试。我试图用它构建一个片段,但我没有成功地用 React 构建一个片段,对此感到抱歉。
我的问题:感谢componentDidMount
我可以切换组件的状态并使淡入效果完美。但是,我很难将淡出放置到位:使用componentWillUnmount
并不能使它起作用。
我的问题的解决方案是什么?我应该如何延迟组件的卸载以进行过渡?