Files
react/docs/more-about-refs.html
T
Paul O’Shannessy 7e16bb70b1 v0.10.0
2014-03-21 13:37:35 -07:00

546 lines
27 KiB
HTML

<!DOCTYPE html>
<!--[if IE]><![endif]-->
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>React | More About Refs</title>
<meta name="viewport" content="width=device-width">
<meta property="og:title" content="React | More About Refs" />
<meta property="og:type" content="website" />
<meta property="og:url" content="http://facebook.github.io/react/docs/more-about-refs.html" />
<meta property="og:image" content="http://facebook.github.io/react/img/logo_og.png" />
<meta property="og:description" content="A JavaScript library for building user interfaces" />
<meta property="fb:app_id" content="623268441017527" />
<link rel="shortcut icon" href="/react/favicon.ico">
<link rel="alternate" type="application/rss+xml" title="React" href="http://facebook.github.io/react/feed.xml">
<link rel="stylesheet" href="/react/css/syntax.css">
<link rel="stylesheet" href="/react/css/codemirror.css">
<link rel="stylesheet" href="/react/css/react.css">
<script type="text/javascript" src="//use.typekit.net/vqa1hcx.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<!--[if lte IE 8]>
<script type="text/javascript" src="/react/js/html5shiv.min.js"></script>
<script type="text/javascript" src="/react/js/es5-shim.min.js"></script>
<script type="text/javascript" src="/react/js/es5-sham.min.js"></script>
<![endif]-->
<script type="text/javascript" src="/react/js/codemirror.js"></script>
<script type="text/javascript" src="/react/js/javascript.js"></script>
<script type="text/javascript" src="/react/js/react.min.js"></script>
<script type="text/javascript" src="/react/js/JSXTransformer.js"></script>
<script type="text/javascript" src="/react/js/live_editor.js"></script>
<script type="text/javascript" src="/react/js/showdown.js"></script>
</head>
<body>
<div class="container">
<div class="nav-main">
<div class="wrap">
<a class="nav-home" href="/react/index.html">
<img class="nav-logo" alt="" src="/react/img/logo_small.png" width="38" height="38">
React
</a>
<ul class="nav-site">
<li><a href="/react/docs/getting-started.html" class="active">docs</a></li>
<li><a href="/react/support.html">support</a></li>
<li><a href="/react/downloads.html">download</a></li>
<li><a href="/react/blog/">blog</a></li>
<li><a href="http://github.com/facebook/react">github</a>
</ul>
</div>
</div>
<section class="content wrap documentationContent">
<div class="nav-docs">
<!-- Docs Nav -->
<div class="nav-docs-section">
<h3>Quick Start</h3>
<ul>
<li>
<a href="/react/docs/getting-started.html">
Getting Started
</a>
</li>
<li>
<a href="/react/docs/tutorial.html">
Tutorial
</a>
</li>
<li>
<a href="/react/docs/thinking-in-react.html">
Thinking in React
</a>
</li>
</ul>
</div>
<div class="nav-docs-section">
<h3>Community Resources</h3>
<ul>
<li>
<a href="/react/docs/videos.html">
Videos
</a>
</li>
<li>
<a href="/react/docs/complementary-tools.html">
Complementary Tools
</a>
</li>
<li>
<a href="/react/docs/examples.html">
Examples
</a>
</li>
</ul>
</div>
<div class="nav-docs-section">
<h3>Guides</h3>
<ul>
<li>
<a href="/react/docs/why-react.html">
Why React?
</a>
</li>
<li>
<a href="/react/docs/displaying-data.html">
Displaying Data
</a>
<ul>
<li>
<a href="/react/docs/jsx-in-depth.html">
JSX in Depth
</a>
</li>
<li>
<a href="/react/docs/jsx-gotchas.html">
JSX Gotchas
</a>
</li>
</ul>
</li>
<li>
<a href="/react/docs/interactivity-and-dynamic-uis.html">
Interactivity and Dynamic UIs
</a>
</li>
<li>
<a href="/react/docs/multiple-components.html">
Multiple Components
</a>
</li>
<li>
<a href="/react/docs/reusable-components.html">
Reusable Components
</a>
</li>
<li>
<a href="/react/docs/forms.html">
Forms
</a>
</li>
<li>
<a href="/react/docs/working-with-the-browser.html">
Working With the Browser
</a>
<ul>
<li>
<a href="/react/docs/more-about-refs.html" class="active">
More About Refs
</a>
</li>
</ul>
</li>
<li>
<a href="/react/docs/tooling-integration.html">
Tooling Integration
</a>
</li>
<li>
<a href="/react/docs/addons.html">
Add-Ons
</a>
<ul>
<li>
<a href="/react/docs/animation.html">
Animation
</a>
</li>
<li>
<a href="/react/docs/two-way-binding-helpers.html">
Two-Way Binding Helpers
</a>
</li>
<li>
<a href="/react/docs/class-name-manipulation.html">
Class Name Manipulation
</a>
</li>
<li>
<a href="/react/docs/test-utils.html">
Test Utilities
</a>
</li>
<li>
<a href="/react/docs/clone-with-props.html">
Cloning Components
</a>
</li>
<li>
<a href="/react/docs/update.html">
Immutability Helpers
</a>
</li>
</ul>
</li>
</ul>
</div>
<div class="nav-docs-section">
<h3>Reference</h3>
<ul>
<li>
<a href="/react/docs/top-level-api.html">
Top-Level API
</a>
</li>
<li>
<a href="/react/docs/component-api.html">
Component API
</a>
</li>
<li>
<a href="/react/docs/component-specs.html">
Component Specs and Lifecycle
</a>
</li>
<li>
<a href="/react/docs/tags-and-attributes.html">
Supported Tags and Attributes
</a>
</li>
<li>
<a href="/react/docs/events.html">
Event System
</a>
</li>
<li>
<a href="/react/docs/dom-differences.html">
DOM Differences
</a>
</li>
<li>
<a href="/react/docs/special-non-dom-attributes.html">
Special Non-DOM Attributes
</a>
</li>
<li>
<a href="/react/docs/reconciliation.html">
Reconciliation
</a>
</li>
</ul>
</div>
<!-- Tips Nav -->
<div class="nav-docs-section">
<h3>Tips</h3>
<ul>
<li>
<a href="/react/tips/introduction.html">Introduction</a>
</li>
<li>
<a href="/react/tips/inline-styles.html">Inline Styles</a>
</li>
<li>
<a href="/react/tips/if-else-in-JSX.html">If-Else in JSX</a>
</li>
<li>
<a href="/react/tips/self-closing-tag.html">Self-Closing Tag</a>
</li>
<li>
<a href="/react/tips/maximum-number-of-jsx-root-nodes.html">Maximum Number of JSX Root Nodes</a>
</li>
<li>
<a href="/react/tips/style-props-value-px.html">Shorthand for Specifying Pixel Values in style props</a>
</li>
<li>
<a href="/react/tips/children-props-type.html">Type of the Children props</a>
</li>
<li>
<a href="/react/tips/controlled-input-null-value.html">Value of null for Controlled Input</a>
</li>
<li>
<a href="/react/tips/componentWillReceiveProps-not-triggered-after-mounting.html">componentWillReceiveProps Not Triggered After Mounting</a>
</li>
<li>
<a href="/react/tips/props-in-getInitialState-as-anti-pattern.html">Props in getInitialState Is an Anti-Pattern</a>
</li>
<li>
<a href="/react/tips/dom-event-listeners.html">DOM Event Listeners in a Component</a>
</li>
<li>
<a href="/react/tips/initial-ajax.html">Load Initial Data via AJAX</a>
</li>
<li>
<a href="/react/tips/false-in-jsx.html">False in JSX</a>
</li>
<li>
<a href="/react/tips/communicate-between-components.html">Communicate Between Components</a>
</li>
<li>
<a href="/react/tips/expose-component-functions.html">Expose Component Functions</a>
</li>
</ul>
</div>
</div>
<div class="inner-content">
<h1>More About Refs</h1>
<div class="subHeader"></div>
<p>After returning the structure of your UI from the render method, you may find yourself wanting to &quot;reach out&quot; and invoke methods on component instances returned from render. Often, doing something like this isn&#39;t necessary for making data flow through your application, because the Reactive data flow always ensures that the most recent <code>props</code> are sent to each child that is output from <code>render()</code>. However there are a few cases, where it still might be necessary or beneficial.</p>
<p>Consider the case when you wish to tell an <code>&lt;input /&gt;</code> element (that exists within your instances sub-hierarchy) to focus after you update its value to be the empty string, <code>&#39;&#39;</code>.</p>
<div class="highlight"><pre><code class="javascript language-javascript" data-lang="javascript"> <span class="kd">var</span> <span class="nx">App</span> <span class="o">=</span> <span class="nx">React</span><span class="p">.</span><span class="nx">createClass</span><span class="p">({</span>
<span class="nx">getInitialState</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="k">return</span> <span class="p">{</span><span class="nx">userInput</span><span class="o">:</span> <span class="s1">&#39;&#39;</span><span class="p">};</span>
<span class="p">},</span>
<span class="nx">handleKeyUp</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">setState</span><span class="p">({</span><span class="nx">userInput</span><span class="o">:</span> <span class="nx">e</span><span class="p">.</span><span class="nx">target</span><span class="p">.</span><span class="nx">value</span><span class="p">});</span>
<span class="p">},</span>
<span class="nx">clearAndFocusInput</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">setState</span><span class="p">({</span><span class="nx">userInput</span><span class="o">:</span> <span class="s1">&#39;&#39;</span><span class="p">});</span> <span class="c1">// Clear the input</span>
<span class="c1">// We wish to focus the &lt;input /&gt; now!</span>
<span class="p">},</span>
<span class="nx">render</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="k">return</span> <span class="p">(</span>
<span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
<span class="o">&lt;</span><span class="nx">div</span> <span class="nx">onClick</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">clearAndFocusInput</span><span class="p">}</span><span class="o">&gt;</span>
<span class="nx">Click</span> <span class="nx">To</span> <span class="nx">Focus</span> <span class="nx">and</span> <span class="nx">Reset</span>
<span class="o">&lt;</span><span class="err">/div&gt;</span>
<span class="o">&lt;</span><span class="nx">input</span>
<span class="nx">value</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">state</span><span class="p">.</span><span class="nx">userInput</span><span class="p">}</span>
<span class="nx">onKeyUp</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">handleKeyUp</span><span class="p">}</span>
<span class="o">/&gt;</span>
<span class="o">&lt;</span><span class="err">/div&gt;</span>
<span class="p">);</span>
<span class="p">}</span>
<span class="p">});</span>
</code></pre></div>
<p>Notice how, in this example, we want to &quot;tell&quot; the input something - something that it cannot infer from its props over time. In this case we want to &quot;tell&quot; it that it should now become focused. However, there are some challenges. What is returned from <code>render()</code> is not your actual composition of &quot;child&quot; components, it is merely a <em>description</em> of the children at a particular instance in time - a snapshot, if you will.</p>
<blockquote>
<p>Note:</p>
<p>Remember, what you return from <code>render()</code> is not your <em>actual</em> rendered children instances. What you return from <code>render()</code> is merely a <em>description</em> of the children instances in your component&#39;s sub-hierarchy at a particular moment in time.</p>
</blockquote>
<p>This means that you should never &quot;hold onto&quot; something that you return from <code>render()</code> and then expect it to be anything meaningful.</p>
<div class="highlight"><pre><code class="javascript language-javascript" data-lang="javascript"> <span class="c1">// counterexample: DO NOT DO THIS!</span>
<span class="nx">render</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">myInput</span> <span class="o">=</span> <span class="o">&lt;</span><span class="nx">input</span> <span class="o">/&gt;</span><span class="p">;</span> <span class="c1">// I&#39;m going to try to call methods on this</span>
<span class="k">this</span><span class="p">.</span><span class="nx">rememberThisInput</span> <span class="o">=</span> <span class="nx">myInput</span><span class="p">;</span> <span class="c1">// input at some point in the future! YAY!</span>
<span class="k">return</span> <span class="p">(</span>
<span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
<span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span><span class="p">...</span><span class="o">&lt;</span><span class="err">/div&gt;</span>
<span class="p">{</span><span class="nx">myInput</span><span class="p">}</span>
<span class="o">&lt;</span><span class="err">/div&gt;</span>
<span class="p">);</span>
<span class="p">}</span>
</code></pre></div>
<p>In this counterexample, the <code>&lt;input /&gt;</code> is merely a <em>description</em> of an <code>&lt;input /&gt;</code>. This description is used to create a <em>real</em> <strong>backing instance</strong> for the <code>&lt;input /&gt;</code>.</p>
<p>So how do we talk to the <em>real</em> backing instance of the input?</p>
<h2><a class="anchor" name="the-ref-attribute"></a>The ref Attribute <a class="hash-link" href="#the-ref-attribute">#</a></h2>
<p>React supports a very special property that you can attach to any component that is output from <code>render()</code>. This special property allows you to refer to the corresponding <strong>backing instance</strong> of anything returned from <code>render()</code>. It is always guaranteed to be the proper instance, at any point in time.</p>
<p>It&#39;s as simple as:</p>
<p><strong>1.</strong> Assign a <code>ref</code> attribute to anything returned from <code>render</code> such as:</p>
<div class="highlight"><pre><code class="html language-html" data-lang="html"> <span class="nt">&lt;input</span> <span class="na">ref=</span><span class="s">&quot;myInput&quot;</span> <span class="nt">/&gt;</span>
</code></pre></div>
<p><strong>2.</strong> In some other code (typically event handler code), access the <strong>backing instance</strong> via <code>this.refs</code> as in:</p>
<div class="highlight"><pre><code class="javascript language-javascript" data-lang="javascript"> <span class="k">this</span><span class="p">.</span><span class="nx">refs</span><span class="p">.</span><span class="nx">myInput</span>
</code></pre></div><h2><a class="anchor" name="completing-the-example"></a>Completing the Example <a class="hash-link" href="#completing-the-example">#</a></h2><div class="highlight"><pre><code class="javascript language-javascript" data-lang="javascript"> <span class="kd">var</span> <span class="nx">App</span> <span class="o">=</span> <span class="nx">React</span><span class="p">.</span><span class="nx">createClass</span><span class="p">({</span>
<span class="nx">getInitialState</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="k">return</span> <span class="p">{</span><span class="nx">userInput</span><span class="o">:</span> <span class="s1">&#39;&#39;</span><span class="p">};</span>
<span class="p">},</span>
<span class="nx">handleKeyUp</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">setState</span><span class="p">({</span><span class="nx">userInput</span><span class="o">:</span> <span class="nx">e</span><span class="p">.</span><span class="nx">target</span><span class="p">.</span><span class="nx">value</span><span class="p">});</span>
<span class="p">},</span>
<span class="nx">clearAndFocusInput</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">setState</span><span class="p">({</span><span class="nx">userInput</span><span class="o">:</span> <span class="s1">&#39;&#39;</span><span class="p">});</span> <span class="c1">// Clear the input</span>
<span class="k">this</span><span class="p">.</span><span class="nx">refs</span><span class="p">.</span><span class="nx">theInput</span><span class="p">.</span><span class="nx">getDOMNode</span><span class="p">().</span><span class="nx">focus</span><span class="p">();</span> <span class="c1">// Boom! Focused!</span>
<span class="p">},</span>
<span class="nx">render</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="k">return</span> <span class="p">(</span>
<span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
<span class="o">&lt;</span><span class="nx">div</span> <span class="nx">onClick</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">clearAndFocusInput</span><span class="p">}</span><span class="o">&gt;</span>
<span class="nx">Click</span> <span class="nx">To</span> <span class="nx">Focus</span> <span class="nx">and</span> <span class="nx">Reset</span>
<span class="o">&lt;</span><span class="err">/div&gt;</span>
<span class="o">&lt;</span><span class="nx">input</span>
<span class="nx">ref</span><span class="o">=</span><span class="s2">&quot;theInput&quot;</span>
<span class="nx">value</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">state</span><span class="p">.</span><span class="nx">userInput</span><span class="p">}</span>
<span class="nx">onKeyUp</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">handleKeyUp</span><span class="p">}</span>
<span class="o">/&gt;</span>
<span class="o">&lt;</span><span class="err">/div&gt;</span>
<span class="p">);</span>
<span class="p">}</span>
<span class="p">});</span>
</code></pre></div>
<p>In this example, our render function returns a description of an <code>&lt;input /&gt;</code> instance. But the true instance is accessed via <code>this.refs.theInput</code>. As long as a child component with <code>ref=&quot;theInput&quot;</code> is returned from render, <code>this.refs.theInput</code> will access the proper instance. This even works on higher level (non-DOM) components such as <code>&lt;Typeahead ref=&quot;myTypeahead&quot; /&gt;</code>.</p>
<h2><a class="anchor" name="summary"></a>Summary <a class="hash-link" href="#summary">#</a></h2>
<p>Refs are a great way to send a message to a particular child instance in a way that would be inconvenient to do via streaming Reactive <code>props</code> and <code>state</code>. They should, however, not be your go-to abstraction for flowing data through your application. By default, use the Reactive data flow and save <code>ref</code>s for use cases that are inherently non-reactive.</p>
<h3><a class="anchor" name="benefits"></a>Benefits: <a class="hash-link" href="#benefits">#</a></h3>
<ul>
<li>You can define any public method on your component classes (such as a reset method on a Typeahead) and call those public methods through refs (such as <code>this.refs.myTypeahead.reset()</code>).</li>
<li>Performing DOM measurements almost always requires reaching out to a &quot;native&quot; component such as <code>&lt;input /&gt;</code> and accessing its underlying DOM node via <code>this.refs.myInput.getDOMNode()</code>. Refs are one of the only practical ways of doing this reliably.</li>
<li>Refs are automatically book-kept for you! If that child is destroyed, its ref is also destroyed for you. No worrying about memory here (unless you do something crazy to retain a reference yourself).</li>
</ul>
<h3><a class="anchor" name="cautions"></a>Cautions: <a class="hash-link" href="#cautions">#</a></h3>
<ul>
<li><em>Never</em> access refs inside of any component&#39;s render method - or while any component&#39;s render method is even running anywhere in the call stack.</li>
<li>If you want to preserve Google Closure Compiler Crushing resilience, make sure to never access as a property what was specified as a string. This means you must access using <code>this.refs[&#39;myRefString&#39;]</code> if your ref was defined as <code>ref=&quot;myRefString&quot;</code>.</li>
<li>If you have not programmed several apps with React, your first inclination is usually going to be to try to use refs to &quot;make things happen&quot; in your app. If this is the case, take a moment and think more critically about where <code>state</code> should be owned in the component hierarchy. Often, it becomes clear that the proper place to &quot;own&quot; that state is at a higher level in the hierarchy. Placing the state there often eliminates any desire to use <code>ref</code>s to &quot;make things happen&quot; - instead, the data flow will usually accomplish your goal.</li>
</ul>
<div class="docs-prevnext">
<a class="docs-prev" href="/react/docs/working-with-the-browser.html">&larr; Prev</a>
<a class="docs-next" href="/react/docs/tooling-integration.html">Next &rarr;</a>
</div>
<div class="fb-comments" data-width="650" data-num-posts="10" data-href="http://facebook.github.io/react/docs/more-about-refs.html"></div>
</div>
</section>
<footer class="wrap">
<div class="left">
A Facebook &amp; Instagram collaboration.<br>
<a href="/react/acknowledgements.html">Acknowledgements</a>
</div>
<div class="right">&copy; 2014 Facebook Inc.</div>
</footer>
</div>
<div id="fb-root"></div>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-41298772-1', 'facebook.github.io');
ga('send', 'pageview');
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=623268441017527";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
</body>
</html>