react hook useRef
时间: 2023-09-01 14:11:13 浏览: 51
The useRef hook is a built-in hook provided by React that enables the creation of a reference to a DOM element or a value that persists between renders. This hook is primarily used to access DOM elements, track state between renders, and store mutable variables.
When we create a reference using useRef, we can access the current value of the reference using the `current` property of the returned object. This object is created once and persists throughout the component's lifetime.
Here's an example:
```
import React, { useRef } from 'react';
function MyComponent() {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus();
};
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleClick}>Focus Input</button>
</div>
);
}
```
In this example, we create a reference to the input element using `useRef`. We then use this reference in the `handleClick` function to focus the input element when the button is clicked.
The `useRef` hook is a powerful tool that allows us to interact with the DOM and store mutable state in a functional component.