什么是 useRef
首先, 我们要实现一个需求 – 点击 button 的时候 input 设置焦点.
createRef API
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import React from "react"; import "./styles.css"; import { createRef } from "react";
export default function App() { const inputElement = createRef(); const focusInput = () => { inputElement.current.focus(); }; return ( <div className="App"> <input ref={inputElement} type="text" /> <button onClick={focusInput}>焦距input</button> </div> ); }
|
同样的, 我们可以使用 useRef 来实现完全相同的结果.
useRef Hook
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import React from "react"; import "./styles.css"; import { useRef } from "react";
export default function App() { const inputElement = useRef(); const focusInput = () => { inputElement.current.focus(); }; return ( <div className="App"> <input ref={inputElement} type="text" /> <button onClick={focusInput}>焦距input</button> </div> ); }
|
createRef 与 useRef 的区别
useRef 在 react hook 中的作用, 正如官网说的, 它像一个变量, 类似于 this , 它就像一个盒子, 你可以存放任何东西. createRef 每次渲染都会返回一个新的引用,而 useRef 每次都会返回相同的引用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| import React, { createRef, useRef } from "react"; import "./styles.css";
const App = () => { const [renderIndex, setRenderIndex] = React.useState(1); const refFromUseRef = useRef(); const refFromCreateRef = createRef();
if (!refFromUseRef.current) { refFromUseRef.current = renderIndex; }
if (!refFromCreateRef.current) { refFromCreateRef.current = renderIndex; }
return ( <> <p>Current render index: {renderIndex}</p> <p> <b>refFromUseRef</b> value: {refFromUseRef.current} </p> <p> <b>refFromCreateRef</b> value:{refFromCreateRef.current} </p>
<button onClick={() => setRenderIndex(prev => prev + 1)}> Cause re-render </button> </> ); };
export default App;
|
就算组件重新渲染, 由于 refFromUseRef 的值一直存在(类似于 this ) , 无法重新赋值.