Spruce up refs docs

Fixes #4651.

(cherry picked from commit 1db20999f0)
This commit is contained in:
Ben Alpert
2015-08-19 16:35:58 -07:00
parent 3154f055cf
commit 9cd6048720
+31 -9
View File
@@ -73,15 +73,15 @@ It's as simple as:
1. Assign a `ref` attribute to anything returned from `render` such as:
```html
<input ref="myInput" />
```
```html
<input ref="myInput" />
```
2. In some other code (typically event handler code), access the **backing instance** via `this.refs` as in:
```javascript
this.refs.myInput
```
```javascript
this.refs.myInput
```
You can access the component's DOM node directly by calling `React.findDOMNode(this.refs.myInput)`.
@@ -92,9 +92,31 @@ The `ref` attribute can be a callback function instead of a name. This callback
It's as simple as assigning a `ref` attribute to anything returned from `render` such as:
```html
<input ref={ function(component){ React.findDOMNode(component).focus();} } />
```
```html
render: function() {
return <TextInput ref={(c) => this._input = c} } />;
},
componentDidMount: function() {
this._input.focus();
},
```
or
```html
render: function() {
return (
<TextInput
ref={function(input) {
if (input != null) {
input.focus();
}
}} />
);
},
```
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.
## Completing the Example