-
Notifications
You must be signed in to change notification settings - Fork 49
/
pp_ref.js
65 lines (57 loc) · 1.55 KB
/
pp_ref.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
import React from 'react'
import ReactDOM from 'react-dom'
// Props Proxy with ref demonstration
function PPHOC(WrappedComponent) {
return class PP extends React.Component {
constructor(props) {
super(props)
this.state = { name: '' }
this.updateName = this.updateName.bind(this)
}
updateName(instance) {
if (instance.instanceName !== this.state.name)
this.setState({name: instance.instanceName})
}
render() {
// Unless you really know what you are doing, dont trigger a state change
// inside the render function, this is just for teaching purposes
const props = Object.assign({}, this.props, {
ref: this.updateName
})
return (
<div>
<h2>
HOC Component
</h2>
<p>
The HOC component gets `instanceName` from the WrappedComponent instance via <br/>
`refs` and saves it in it's own state:
</p>
<pre>{JSON.stringify(this.state, null, 2)}</pre>
<WrappedComponent {...props}/>
</div>
)
}
}
}
class Example extends React.Component {
constructor(props) {
super(props)
this.instanceName = 'han solo'
}
render() {
return (
<div>
<h2>
Wrapped Component
</h2>
<p>
Props
</p>
<pre>{JSON.stringify(this.props, null, 2)}</pre>
</div>
)
}
}
const EnhancedExample = PPHOC(Example)
ReactDOM.render(<EnhancedExample date={(new Date).toISOString()}/>, document.getElementById('root'))