在 React 使用全屏 Loading 效果

到哪都會用到的 Loading。

簡述

1. 先下載套件

來源:https://www.npmjs.com/package/react-loading-overlay#styles-with-emotion

1
npm install react-loading-overlay

2. 用 styled component 撰寫全屏樣式

附 code 之前先解釋一下邏輯,LoadingOverlay 預設的 HTML 結構長這樣:

  • div.wrapper 容器
    • div.overlay 載入畫面

這裡設定的東西是「容器」,因為希望有全屏效果,所以使用 fixed 來做:

1
2
3
4
5
6
7
const StyledLoader = styled(LoadingOverlay)`
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
`;

3. 把改好的 Component 放上去

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function App () {
retrun (
{isLoading && (
<StyledLoader
active={isLoading}
spinner={true}
text="Loading your content..."
></StyledLoader>
)}
<Component1 />
<Component2 />
<Component3 />
)
}

補充:之所以要用 && 條件渲染是因為 LoadingOverlay 關閉時並不會把 div.wrapper 移除,而 div.wrapper 又正好放在最頂層,等於說會蓋在所有元素之上,沒辦法做任何操作。

所以才得加上條件渲染的方式來解決這個問題,不過要注意用這種方式的話 fade 的效果就會消失。

如果不想這麼麻煩的話,可以把 CSS 改成這樣:

1
2
3
4
5
6
7
8
9
10
const StyledLoader = styled(LoadingOverlay)`
// 選到下面的 div.overlay
& > ._loading_overlay_overlay {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
`;

這樣就完成囉~

loading

附註

雖然照上面的作法應該就沒問題了,但應該會一直出現 Warning 訊息,像這樣:

warn

簡單來說應該是 styles 的 propType 不正確的關係,但我就沒有要傳 styleds 啊!

所以後來找到 這篇 的 issue,但作者似乎都不回應了,所以只好這樣子解:

1
2
import LoadingOverlay from 'react-loading-overlay';
LoadingOverlay.propTypes = undefined;

或者也可以用別人修正過後的 套件 來試試看。

在 React 引入圖片的方式 React 當初始值是 API 的資料怎麼辦?
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×