This repository was archived by the owner on Sep 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 113
/
Copy path06 - Refs.js
118 lines (90 loc) · 2.5 KB
/
06 - Refs.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
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
// This is a refs proposal that uses callbacks instead of strings. The callback
// can be easily statically typed and solves most use cases.
// When a ref is attached, it gets passed the instance as the first argument.
// When a ref is detached, the callback is invoked with null as the argument.
// refs on DOM nodes gives the DOM node handle directly, not an intermediate
// form.
class Foo {
myDivRef : ?HTMLDivElement;
handleTick() {
this.setState({ width: this.myDivRef.offsetWidth });
}
render() {
return (
<C tick={this.handleTick}>
<div ref={node => this.myDivRef = node} />
<CustomComponent context={() => this.myDivRef} />
</C>
);
}
}
// It's possible to distinguish whether a ref as ever been mounted or if it has
// been mounted during this particular reconciliation phase.
class Component {
buttonWasEverMounted : boolean;
buttonWasMountedThisPass : boolean;
button : ?Button;
mountButtonRef = button => {
if (button) {
this.buttonWasEverMounted = true;
this.buttonWasMountedThisPass = true;
}
this.button = button;
}
componentWillMount() {
this.componentWillUpdate();
}
componentDidMount() {
this.componentDidUpdate();
}
componentWillUpdate() {
this.buttonWasMountedThisPass = false;
}
componentDidUpdate() {
if (this.buttonWasEverMounted) {
console.log('button was mounted at least once');
}
if (this.buttonWasMountedThisPass) {
console.log('button was mounted during this render pass');
}
}
render() {
return <Button ref={this.mountButtonRef} />;
}
}
// In a future world where every callback is also implemented as an Observer,
// we can pass a subject to the ref to build Observable compositions on top
// of a ref.
class Foo {
myTick = new Rx.Subject();
myDiv = new Rx.Subject();
observe() {
var widths = this.myDiv.map(myDivRef => myDivRef.offsetWidth);
return {
width: this.myTick.combineLatest(widths, (e, width) => width)
};
}
render() {
return (
<C tick={this.myTick}>
<div ref={this.myDiv} />
<CustomComponent context={this.myDiv} />
</C>
);
}
}
// Getting your "own" DOM node is still possible with a call to traverse the
// composites until you get to the DOM node.
class Foo {
handleTick() {
var node = React.findDOMNode(this);
this.setState({ width: node.offsetWidth });
}
render() {
return (
<C tick={this.handleTick}>
<div />
</C>
);
}
}