-
Notifications
You must be signed in to change notification settings - Fork 404
/
14-references.html
57 lines (49 loc) · 1.84 KB
/
14-references.html
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
<!doctype html>
<title>14 References - React From Zero</title>
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/[email protected]/create-react-class.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<div id="app"></div>
<script type="text/babel">
// Sometimes we need some state from an element or a component
// or it has to be directly modified somehow. For
// this case, we can tell React to create references.
var RefComponent = createReactClass({
// First we tell React to render an input with a ref callback, it
// will be called, when the DOM of the input element is available
render: function() {
return (
<div>
<input ref={this.handleRef} />
<button onClick={this.handleClick}>Do Something</button>
</div>
);
},
// This callback is called when the input element was mounted into
// the DOM and again, with null, when it was unmounted again
// For elements the rendered DOM node will be stored
// For components the instance of the component will be stored.
handleRef(nameInput) {
// We save a reference to it for later use.
this.nameInput = nameInput;
},
// This callback is called when the button is clicked
// and uses this.nameInput to read out the value of the input.
handleClick: function() {
console.log(this.nameInput.value);
}
});
// Since references are local to their component
// they can be used as local IDs to get elements
// and don't override each other when another
// instance of the component is created
var reactElement = (
<div>
<RefComponent />
<RefComponent />
<RefComponent />
</div>
);
ReactDOM.render(reactElement, document.getElementById("app"));
</script>