这是我在 2019 年解决这个问题的方法,同时制作了一个加载微调器。我正在使用 React 功能组件。
我有一个父App组件,它有一个子Spinner组件。
应用程序具有应用程序是否正在加载的状态。应用加载时,Spinner正常渲染。当应用程序未加载时(isLoading
为 false)Spinner使用 prop 渲染shouldUnmount
。
应用程序.js:
import React, {useState} from 'react';
import Spinner from './Spinner';
const App = function() {
const [isLoading, setIsLoading] = useState(false);
return (
<div className='App'>
{isLoading ? <Spinner /> : <Spinner shouldUnmount />}
</div>
);
};
export default App;
Spinner具有是否隐藏的状态。一开始,使用默认的 props 和 state,Spinner是正常渲染的。类Spinner-fadeIn
动画它淡入。当SpinnershouldUnmount
接收到它与类一起渲染的道具时Spinner-fadeOut
,动画它淡出。
但是,我还希望组件在淡出后卸载。
此时我尝试使用onAnimationEnd
React 合成事件,类似于上面@pranesh-ravi 的解决方案,但它不起作用。相反,我曾经setTimeout
将状态设置为隐藏,延迟与动画长度相同。Spinner将在延迟后更新isHidden === true
,并且不会渲染任何内容。
这里的关键是父级并没有卸载子级,它告诉子级何时卸载,子级在处理完自己的卸载业务后自行卸载。
微调器.js:
import React, {useState} from 'react';
import './Spinner.css';
const Spinner = function(props) {
const [isHidden, setIsHidden] = useState(false);
if(isHidden) {
return null
} else if(props.shouldUnmount) {
setTimeout(setIsHidden, 500, true);
return (
<div className='Spinner Spinner-fadeOut' />
);
} else {
return (
<div className='Spinner Spinner-fadeIn' />
);
}
};
export default Spinner;
微调器.css:
.Spinner {
position: fixed;
display: block;
z-index: 999;
top: 50%;
left: 50%;
margin: -40px 0 0 -20px;
height: 40px;
width: 40px;
border: 5px solid #00000080;
border-left-color: #bbbbbbbb;
border-radius: 40px;
}
.Spinner-fadeIn {
animation:
rotate 1s linear infinite,
fadeIn .5s linear forwards;
}
.Spinner-fadeOut {
animation:
rotate 1s linear infinite,
fadeOut .5s linear forwards;
}
@keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@keyframes fadeOut {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
@keyframes rotate {
100% {
transform: rotate(360deg);
}
}