-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample-2.js
More file actions
42 lines (35 loc) · 831 Bytes
/
example-2.js
File metadata and controls
42 lines (35 loc) · 831 Bytes
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
// 案例 2
const MyReact = (function () {
let _val // 在模块作用域内保留状态
return {
render(Component) {
const Comp = Component()
Comp.render()
return Comp
},
useState(initialValue) {
// 每次调用时,增加 _val 值赋值判断
const state = _val || initialValue
function setState(newVal) {
_val = newVal
}
return [state, setState]
}
}
})()
// [续] 案例 2
function Counter() {
const [count, setCount] = MyReact.useState(0) // 使用之前实现的 useState()
return {
click() {
setCount(count + 1)
},
render() {
console.log('[render]', { count: count })
}
}
}
let App
App = MyReact.render(Counter) // [render] { count: 0 }
App.click()
App = MyReact.render(Counter) // [render] { count: 1 }