<style> .description{ letter-spacing : 2px; line-height : 28px; text-align : justify; } .firstLine{ margin-left : 30px; } b{ font-weight : 700; } </style> # React useRef [影片](https://www.youtube.com/watch?v=pW6zqsff8S8&feature=youtu.be) <div class="description"> useRef通常是用來訪問DOM元素,透過useRef能夠操作元素本身,較常用的為利用useRef取得input的值,如果input是採用useState來取得值的話,那每次對input輸入文字時都會重新渲染畫面(rerender),因為state改變了,但如果利用useRef的話並不會有重新渲染的問題,因為它是直接進入DOM元素內取得值。</div> <br> <div class="description"> 讓我們來看看使用useState取得input值的程式碼範例 </div> ```javascript= import { useState } from "react"; function App() { const [name, setName] = useState(""); console.log("APP render") const clickHandler = () => { console.log(name); }; return ( <> <h1>Hello World</h1> <input type="text" onChange={(e) => setName(e.target.value)} /> {name} <button onClick={clickHandler}>click</button> </> ); } export default App; ``` <div class="description"> 以上程式碼每當input被輸入的時候,都會重新渲染畫面,<b>所以每輸入一次就會在console看到"APP render"</b>,這在效能上可能會有問題。 </div> <br> <div class="description"> 接著來看看使用useRef取得input值的程式碼範例 </div> ```javascript= import { useRef } from "react"; function App() { const inputRef = useRef(null); console.log("APP render"); const clickHandler = () => { console.log(inputRef.current.value); //can use inputRef.current.focus() }; return ( <> <h1>Hello World</h1> <input type="text" ref={inputRef} /> <button onClick={clickHandler}>click</button> </> ); } export default App; ``` <div class="description"> 透過useRef,我們能直接訪問DOM元素,<b>在程式碼第7行的inputRef.current.value就相當等於我們使用原生javascript的e.target.value</b>,除此之外我們也可以利用DOM的其他方法,<b>像是focus()</b>,讓使用者的瀏覽器焦距在input輸入框內。 </div>
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up