From 8e468a830e6260e9556f00f0cbe5b001f8f3c454 Mon Sep 17 00:00:00 2001 From: Ben Alpert Date: Wed, 19 Aug 2015 16:14:35 -0700 Subject: [PATCH] Spruce up refs docs Fixes #4651. --- docs/08.1-more-about-refs.md | 40 ++++++++++++++++++++++++++++-------- 1 file changed, 31 insertions(+), 9 deletions(-) diff --git a/docs/08.1-more-about-refs.md b/docs/08.1-more-about-refs.md index 9cd8ac35..a54d02ff 100644 --- a/docs/08.1-more-about-refs.md +++ b/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 - - ``` + ```html + + ``` 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 - - ``` +```html + render: function() { + return this._input = c} } />; + }, + componentDidMount: function() { + this._input.focus(); + }, +``` + +or + +```html + render: function() { + return ( + + ); + }, +``` + +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