<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Allen Hsieh on Medium]]></title>
        <description><![CDATA[Stories by Allen Hsieh on Medium]]></description>
        <link>https://medium.com/@allen_hsieh?source=rss-81b55a7f6f3f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*jjDT5XSzx8_6KkM6.</url>
            <title>Stories by Allen Hsieh on Medium</title>
            <link>https://medium.com/@allen_hsieh?source=rss-81b55a7f6f3f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 07:43:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@allen_hsieh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Ref 屬性 與 DOM 元素]]></title>
            <link>https://medium.com/4cats-io/24hrs-react-101-b287ffad1070?source=rss-81b55a7f6f3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b287ffad1070</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Allen Hsieh]]></dc:creator>
            <pubDate>Tue, 21 Feb 2017 04:52:53 GMT</pubDate>
            <atom:updated>2017-02-22T07:23:28.556Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jGVkSlEbhPhkouhMnYLF0Q.jpeg" /></figure><p>React, 翻譯文章, 如何在元件中取得 DOM 元素</p><p>出處：這篇文章的內容是翻譯自官方文件（<a href="https://facebook.github.io/react/docs/refs-and-the-dom.html">Refs and the DOM</a>），然後加上筆者的詮釋。</p><h3>為什麼需要 ref 屬性？</h3><p>在 React 的世界裡，父元件（parent components）透過 props 將資料傳遞給 子元件（children components），另外子元件也會在 state 存放一些狀態與資料。但某些情況的時候，我們需要能夠存取自己 render 的 DOM 元素或子元件，例如：</p><ul><li>管理聚焦、文字選擇，媒體播放。</li><li>觸發動畫</li><li>整合第三方的 DOM 函式庫</li></ul><p>備註：不要過度使用 ref，例如父元件要控制一個對話框的子元件，與其把 open &amp; close 兩個函式暴露給父元件，不如父元件透過 props 傳遞 isOpen 這個屬性給子元件。</p><h3>在 DOM 元素裡使用 ref 屬性</h3><p>以下面這個例子來說，CustomTextInput 這個元件有兩個 HTML 元素，一個輸入框與一個按鈕。當按鈕被按下的時候，我們希望游標可以聚焦在輸入框。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c51a3f994904553334aaad76102858f/href">https://medium.com/media/0c51a3f994904553334aaad76102858f/href</a></iframe><p>重點就在於按鈕的 callback 函式（focus，第 2 行），要如何能夠存取到輸入框這個 DOM 元件。請注意看第 8 行的地方，我們使用了 ref 這個屬性，在這個屬性裡面我們可以放一個 callback 函式，而在這個函式裡面，我們把輸入框 DOM 元件掛在 textInput 這個變數下，接著我們就可以在 focus 這個函式中，透過 this.textInput 來存取到該元素。</p><h3>Ref 屬性是如何運作的？</h3><p>當 React 元件被 mount 起來的時候，ref 裡面設定的 callback 會被呼叫，並且把 DOM 元素當參數傳遞進來，在 React 元件被 unmount 的時候，ref callback 會被再呼叫一次，這次傳遞進來的參數就是 null。（因為該 DOM 元素要被消滅了）</p><h3>React 元件也適用 ref 屬性</h3><p>Ref 屬性也適用在 react 元件，讓父元件可以存取到子元件，例如下面的範例：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/786e6dfb2c4d01969c10da9943e8f170/href">https://medium.com/media/786e6dfb2c4d01969c10da9943e8f170/href</a></iframe><p>但前提是子元件必須是 Class 元件，白話文就是宣告的方式必須像下面這樣</p><pre>class CustomTextInput extends React.Component</pre><p>如果子元件是 Functional 元件（直接透過 function 建立的 react 元件），那就無法使用。</p><h3>不要過度使用 ref</h3><p>當在撰寫元件的時候，如果第一個想法是透過 ref 來達到你要的功能時，建議您停下腳步，謹慎地想一想有沒有更好的方式，state 是不是在恰當的位置。通常有更簡單的解決方式，例如將這個 state 往上提。</p><h3>在 ref 屬性中使用字串</h3><p>在觀看別人的程式碼的時候，你可能會看到 ref 屬性裡面塞的是「字串」，例如：</p><pre>&lt;input type=&quot;text&quot; ref=&quot;firstname&quot;&gt;&lt;/input&gt;<br>&lt;input type=&quot;text&quot; ref=&quot;lastname&quot;&gt;&lt;/input&gt;</pre><p>然後透過 this.refs 來存取</p><pre>getFullName() {<br>  return this.refs.firstname.value + this.refs.lastname.value;<br>}</pre><p>這個 pattern 已經在官網建議不要這樣使用了，首先在某些情境下會發生問題（<a href="https://github.com/facebook/react/pull/8333#issuecomment-271648615">細節可以看這邊</a>，英文版），另外在 react 未來的版本中，有考慮要移除他。</p><h3>工商時間</h3><h4><a href="http://www.4cats.io/p/24hrs-react-101?utm_source=medium.com&amp;utm_campaign=react_blog&amp;utm_medium=blog&amp;utm_term=refs">24 小時，React 快速入門</a></h4><p>讓你用最短時間，充分體會 React 的脈絡思維</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b287ffad1070" width="1" height="1" alt=""><hr><p><a href="https://medium.com/4cats-io/24hrs-react-101-b287ffad1070">Ref 屬性 與 DOM 元素</a> was originally published in <a href="https://medium.com/4cats-io">前端魔法研究室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>