@samitouri / QOS-React-2 / commits / 1db20999f0

Spruce up refs docs

Fixes #4651.

Ben Alpert committed Aug 19, 2015 at 16:14 UTC 1db20999f0336cfacc6af5ee6f5a77803d74381b
1 file changed +31 -9
docs/docs/08.1-more-about-refs.md
+31 -9
@@ -73,15 +73,15 @@ It's as simple as:
73
74 1. Assign a `ref` attribute to anything returned from `render` such as:
75
76 - ```html
77 - <input ref="myInput" />
78 - ```
76 + ```html
77 + <input ref="myInput" />
78 + ```
79
80 2. In some other code (typically event handler code), access the **backing instance** via `this.refs` as in:
81
82 - ```javascript
83 - this.refs.myInput
84 - ```
82 + ```javascript
83 + this.refs.myInput
84 + ```
85
86 You can access the component's DOM node directly by calling `React.findDOMNode(this.refs.myInput)`.
87
@@ -92,9 +92,31 @@ The `ref` attribute can be a callback function instead of a name. This callback
92
93 It's as simple as assigning a `ref` attribute to anything returned from `render` such as:
94
95 - ```html
96 - <input ref={ function(component){ React.findDOMNode(component).focus();} } />
97 - ```
95 +```html
96 + render: function() {
97 + return <TextInput ref={(c) => this._input = c} } />;
98 + },
99 + componentDidMount: function() {
100 + this._input.focus();
101 + },
102 +```
103 +
104 +or
105 +
106 +```html
107 + render: function() {
108 + return (
109 + <TextInput
110 + ref={function(input) {
111 + if (input != null) {
112 + input.focus();
113 + }
114 + }} />
115 + );
116 + },
117 +```
118 +
119 +Note that when the referenced component is unmounted and whenever the ref changes, the old ref will be called with `null` as an argument. This prevents memory leaks in the case that the instance is stored, as in the first example. Note that when writing refs with inline function expressions as in the examples here, React sees a different function object each time so on every update, ref will be called with `null` immediately before it's called with the component instance.
120
121
122 ## Completing the Example