mirror of
https://github.com/facebook/react.git
synced 2025-11-01 09:12:30 +00:00
Spruce up refs docs
Fixes #4651.
(cherry picked from commit 1db20999f0)
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user