-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.tsx
111 lines (98 loc) · 2.41 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/**
* @file index.ts
* @author imcuttle
*
*/
import * as React from 'react'
import * as p from 'prefix-classname'
import { FunctionComponent, ComponentClass } from 'react'
const cx = p('')
const c = p('rcp-loading-wrapper__')
export type TypeLoadingWrapperProps = {
isLoading: boolean
renderLoadingDelayMs?: number
withDelayRenderFirstly?: boolean
className?: string
LoadingComponent: FunctionComponent | ComponentClass | string
}
export default class LoadingWrapper extends React.PureComponent<TypeLoadingWrapperProps> {
static defaultProps = {
isLoading: false,
// 渲染Loading 延迟ms
renderLoadingDelayMs: 1000,
// 是否首次的时候 delay 渲染 loading
withDelayRenderFirstly: false,
LoadingComponent: null
}
state = {
couldRender: false
}
timer = null
killTimer() {
clearTimeout(this.timer)
this.timer = null
}
register() {
if (this.props.renderLoadingDelayMs) {
if (this.timer) {
this.killTimer()
}
this.timer = setTimeout(() => {
this.setState({
couldRender: true
})
}, this.props.renderLoadingDelayMs)
}
}
updateTimer(prevProps, isFirst = false) {
if (!this.props.isLoading) {
this.killTimer()
this.setState({
couldRender: false
})
return
}
const couldDelay = (isFirst && this.props.withDelayRenderFirstly) || !isFirst
if (!couldDelay) {
if (this.props.isLoading) {
this.killTimer()
this.setState({
couldRender: true
})
}
} else {
if (this.props.renderLoadingDelayMs) {
if (this.props.isLoading) {
this.register()
}
} else {
if (this.props.isLoading) {
this.killTimer()
this.setState({
couldRender: true
})
}
}
}
}
componentDidMount() {
this.updateTimer({ isLoading: false }, true)
}
componentDidUpdate(prevProps) {
this.updateTimer(prevProps)
}
get couldRender() {
return this.state.couldRender
}
render() {
const { className, LoadingComponent } = this.props
return (
<div className={c('container', !this.couldRender && 'hide', className)}>
{this.props.children}
<div className={c('mask')}>
<div className={c('main')}>{!!LoadingComponent && React.createElement(LoadingComponent)}</div>
</div>
</div>
)
}
}