reacthook useRef
时间: 2023-09-01 14:10:51 浏览: 104
React Hook `useRef` is a function that returns a mutable object with a `current` property that can be used to store and access a value across renders. It is similar to creating an instance property on a class component.
The `useRef` hook is used to:
1. Store a value that persists across renders without triggering a re-render.
2. Access the properties of a DOM node or a React component instance.
The most common use case of `useRef` is to access the DOM nodes, such as:
1. Focus an input element
2. Scroll a container
3. Measure the size of an element
Example:
```
import React, { useRef } from 'react';
function Example() {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus();
};
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleClick}>Focus Input</button>
</div>
);
}
```
In the above example, we are using `useRef` to store a reference to the input element, and in the `handleClick` function, we are accessing that reference to call the `focus` method on the input element.
阅读全文