This repository has been archived by the owner on Feb 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 568
/
11.extra-3.js
71 lines (65 loc) · 1.58 KB
/
11.extra-3.js
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
// The provider pattern
// Extra credit: support render props
import React, {Fragment} from 'react'
import {Switch} from '../switch'
const ToggleContext = React.createContext()
function ToggleConsumer(props) {
return (
<ToggleContext.Consumer {...props}>
{context => {
if (!context) {
throw new Error(
`Toggle.Consumer cannot be rendered outside the Toggle component`,
)
}
return props.children(context)
}}
</ToggleContext.Consumer>
)
}
class Toggle extends React.Component {
static Consumer = ToggleConsumer
toggle = () =>
this.setState(
({on}) => ({on: !on}),
() => this.props.onToggle(this.state.on),
)
state = {on: false, toggle: this.toggle}
render() {
const {children, ...rest} = this.props
const ui =
typeof children === 'function' ? children(this.state) : children
return (
<ToggleContext.Provider value={this.state} {...rest}>
{ui}
</ToggleContext.Provider>
)
}
}
const Layer1 = () => <Layer2 />
const Layer2 = () => (
<Toggle.Consumer>
{({on}) => (
<Fragment>
{on ? 'The button is on' : 'The button is off'}
<Layer3 />
</Fragment>
)}
</Toggle.Consumer>
)
const Layer3 = () => <Layer4 />
const Layer4 = () => (
<Toggle.Consumer>
{({on, toggle}) => <Switch on={on} onClick={toggle} />}
</Toggle.Consumer>
)
function Usage({
onToggle = (...args) => console.log('onToggle', ...args),
}) {
return (
<Toggle onToggle={onToggle}>
<Layer1 />
</Toggle>
)
}
export {Toggle, Usage as default}