-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
Copy pathreact.ts
259 lines (219 loc) · 7.04 KB
/
react.ts
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import type * as React from 'react'
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import type { AppConfig } from '@tarojs/taro'
import { isFunction, ensure, EMPTY_OBJ } from '@tarojs/shared'
import { Current } from '../current'
import { AppInstance, ReactPageComponent, PageProps, Instance, ReactAppInstance } from './instance'
import { document } from '../bom/document'
import { injectPageInstance } from './common'
import { isBrowser } from '../env'
import { options } from '../options'
import { Reconciler } from '../reconciler'
import { incrementId } from '../utils'
function isClassComponent (R: typeof React, component): boolean {
return isFunction(component.render) ||
!!component.prototype?.isReactComponent ||
component.prototype instanceof R.Component // compat for some others react-like library
}
export function connectReactPage (
R: typeof React,
id: string
) {
const h = R.createElement
return (component: ReactPageComponent): React.ComponentClass<PageProps> => {
// eslint-disable-next-line dot-notation
const isReactComponent = isClassComponent(R, component)
const inject = (node?: Instance) => node && injectPageInstance(node, id)
const refs = isReactComponent ? { ref: inject } : {
forwardedRef: inject,
// 兼容 react-redux 7.20.1+
reactReduxForwardedRef: inject
}
if (PageContext === EMPTY_OBJ) {
PageContext = R.createContext('')
}
return class Page extends R.Component<PageProps, { hasError: boolean }> {
state = {
hasError: false
}
static getDerivedStateFromError (error: Error) {
console.warn(error)
return { hasError: true }
}
// React 16 uncaught error 会导致整个应用 crash,
// 目前把错误缩小到页面
componentDidCatch (error: Error, info: React.ErrorInfo) {
console.warn(error)
console.error(info.componentStack)
}
render () {
const children = this.state.hasError
? []
: h(PageContext.Provider, { value: id }, h(component, {
...this.props,
...refs
}))
if (isBrowser) {
return h(
'div',
{ id, className: 'taro_page' },
children
)
}
return h(
'root',
{ id },
children
)
}
}
}
}
// 初始值设置为 any 主要是为了过 TS 的校验
export let R: typeof React = EMPTY_OBJ
export let PageContext: React.Context<string> = EMPTY_OBJ
let ReactDOM
type PageComponent = React.CElement<PageProps, React.Component<PageProps, any, any>>
function setReconciler () {
const hostConfig: Reconciler<React.FunctionComponent<PageProps> | React.ComponentClass<PageProps>> = {
getLifecyle (instance, lifecycle) {
if (lifecycle === 'onShow') {
lifecycle = 'componentDidShow'
} else if (lifecycle === 'onHide') {
lifecycle = 'componentDidHide'
}
return instance[lifecycle] as Function
},
mergePageInstance (prev, next) {
if (!prev || !next) return
// 子组件使用 lifecycle hooks 注册了生命周期后,会存在 prev,里面是注册的生命周期回调。
Object.keys(prev).forEach(item => {
if (isFunction(next[item])) {
next[item] = [next[item], ...prev[item]]
} else {
next[item] = [...(next[item] || []), ...prev[item]]
}
})
}
}
if (isBrowser) {
hostConfig.createPullDownComponent = (el, _, R: typeof React) => {
const isReactComponent = isClassComponent(R, el)
return R.forwardRef((props, ref) => {
const newProps: React.Props<any> = { ...props }
if (isReactComponent) {
newProps.ref = ref
}
return R.createElement('taro-pull-to-refresh', null, R.createElement(el, newProps))
})
}
hostConfig.findDOMNode = (inst) => {
return ReactDOM.findDOMNode(inst)
}
}
options.reconciler(hostConfig)
}
const pageKeyId = incrementId()
export function createReactApp (App: React.ComponentClass, react: typeof React, reactdom, config: AppConfig) {
R = react
ReactDOM = reactdom
ensure(!!ReactDOM, '构建 React/Nerv 项目请把 process.env.FRAMEWORK 设置为 \'react\'/\'nerv\' ')
const ref = R.createRef<ReactAppInstance>()
const isReactComponent = isClassComponent(R, App)
setReconciler()
let wrapper: AppWrapper
class AppWrapper extends R.Component {
// run createElement() inside the render function to make sure that owner is right
private pages: Array<() => PageComponent> = []
private elements: Array<PageComponent> = []
public mount (component: React.ComponentClass<PageProps>, id: string, cb: () => void) {
const key = id + pageKeyId()
const page = () => R.createElement(component, { key, tid: id })
this.pages.push(page)
this.forceUpdate(cb)
}
public unmount (id: string, cb: () => void) {
for (let i = 0; i < this.elements.length; i++) {
const element = this.elements[i]
if (element.props.tid === id) {
this.elements.splice(i, 1)
break
}
}
this.forceUpdate(cb)
}
public render () {
while (this.pages.length > 0) {
const page = this.pages.pop()!
this.elements.push(page())
}
let props: React.Props<any> | null = null
if (isReactComponent) {
props = { ref }
}
return R.createElement(
App,
props,
isBrowser ? R.createElement('div', null, this.elements.slice()) : this.elements.slice()
)
}
}
const app: AppInstance = Object.create({
render (cb: () => void) {
wrapper.forceUpdate(cb)
},
mount (component: ReactPageComponent, id: string, cb: () => void) {
const page = connectReactPage(R, id)(component)
wrapper.mount(page, id, cb)
},
unmount (id: string, cb: () => void) {
wrapper.unmount(id, cb)
}
}, {
config: {
writable: true,
enumerable: true,
configurable: true,
value: config
},
onLaunch: {
enumerable: true,
value (options) {
// eslint-disable-next-line react/no-render-return-value
wrapper = ReactDOM.render(R.createElement(AppWrapper), document.getElementById('app'))
const app = ref.current
Current.router = {
params: options?.query,
...options
}
if (app != null && isFunction(app.onLaunch)) {
app.onLaunch(options)
}
}
},
onShow: {
enumerable: true,
value (options) {
const app = ref.current
Current.router = {
params: options?.query,
...options
}
if (app != null && isFunction(app.componentDidShow)) {
app.componentDidShow(options)
}
}
},
onHide: {
enumerable: true,
value (options: unknown) {
const app = ref.current
if (app != null && isFunction(app.componentDidHide)) {
app.componentDidHide(options)
}
}
}
})
Current.app = app
return Current.app
}