React useRef Hook(钩子)
useRef 钩子让值在渲染时持久化。
它可用于存储一个可变值,在更新时不会导致重新渲染。
它可以用来直接访问 DOM 元素。
不会导致重新渲染
如果我们试图计算应用程序使用 useState 钩子渲染的次数,我们将陷入无限循环,因为这个钩子本身会导致重新渲染。
为了避免这种情况,我们可以使用 useRef 钩子。
实例:
使用 useRef 跟踪应用程序渲染。
import { useState, useEffect, useRef } from "react";import ReactDOM from "react-dom";function App() {const [inputValue, setInputValue] = useState("");const count = useRef(0);useEffect(() => {count.current = count.current + 1;});return (<><inputtype="text"value={inputValue}onChange={(e) => setInputValue(e.target.value)}/><h1>Render Count: {count.current}</h1></>);}ReactDOM.render(<App />, document.getElementById("root"));
useRef() 只返回一个项目。它返回一个名为 current 的对象。
初始化 useRef 时,我们设置初始值:useRef(0)。
就像这样:
const count={current:0}。我们可以使用 count.current 访问计数。在计算机上运行此操作,然后尝试键入输入,以查看应用程序渲染计数是否增加。
访问 DOM 元素
通常,我们希望让 React 处理所有 DOM 操作。
但在某些情况下,可以使用 useRef 而不会引起问题。
在 React 中,我们可以向元素添加 ref 属性,以便在 DOM 中直接访问它。
实例:
使用 useRef 聚焦输入框:
import { useRef } from "react";import ReactDOM from "react-dom";function App() {const inputElement = useRef();const focusInput = () => {inputElement.current.focus();};return (<><input type="text" ref={inputElement} /><button onClick={focusInput}>Focus Input</button></>);}ReactDOM.render(<App />, document.getElementById("root"));
跟踪状态更改
useRef 钩子还可以用来跟踪以前的状态值。
这是因为我们能够在渲染时持久化 useRef 值。
实例:
使用 useRef 跟踪以前的状态值:
import { useState, useEffect, useRef } from "react";import ReactDOM from "react-dom";function App() {const [inputValue, setInputValue] = useState("");const previousInputValue = useRef("");useEffect(() => {previousInputValue.current = inputValue;}, [inputValue]);return (<><inputtype="text"value={inputValue}onChange={(e) => setInputValue(e.target.value)}/><h2>Current Value: {inputValue}</h2><h2>Previous Value: {previousInputValue.current}</h2></>);}ReactDOM.render(<App />, document.getElementById("root"));
这次我们结合使用 useState 、useffect 和 useRef 来跟踪上一个状态。
在 useEffect 中,每次通过在输入字段中输入文本来更新 inputValue 时,我们都会更新 useRef 当前值。