Browse Source

Spruce up refs docs

Fixes #4651.
main
Ben Alpert 10 years ago
parent
commit
8e468a830e
  1. 40
      docs/08.1-more-about-refs.md

40
docs/08.1-more-about-refs.md

@ -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

Loading…
Cancel
Save