📜  反应钩子中的 useref - Javascript (1)

📅  最后修改于: 2023-12-03 15:07:25.097000             🧑  作者: Mango

useRef in React Hooks - Javascript

useRef is one of the React hooks that can be used to reference a DOM element or a value in our code. It returns a mutable ref object that can be updated, and accessing its .current property allows us to get or set the value of the reference.

Basic Usage
import React, { useRef } from 'react'

function MyComponent() {
  const inputRef = useRef(null);

  const handleClick = () => {
    inputRef.current.focus();
  }

  return (
    <>
      <input type="text" ref={inputRef} />
      <button onClick={handleClick}>Focus the input</button>
    </>
  )
}

In this example, we've created a simple MyComponent that renders an input and a button. We've used useRef to create a reference to the input element, and we've passed that reference to the input's ref prop. When the button is clicked, we call the handleClick function, which uses the current property of the inputRef to get a reference to the input element and focus it.

Other Usages
Keeping Values Between Renders

We can also use useRef to keep values between renders of a component. This is useful when we don't want a value to trigger a re-render, but still need to be able to access it in our functional component.

import React, { useState, useRef } from 'react'

function MyComponent() {
  const [count, setCount] = useState(0);
  const prevCountRef = useRef(0);

  useEffect(() => {
    prevCountRef.current = count;
  });

  function handleClick() {
    setCount(count + 1);
  }

  return (
    <div>
      <p>Current Count: {count}</p>
      <p>Previous Count: {prevCountRef.current}</p>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
}

In this example, we're using useRef to keep track of the previous value of count so that we can display it alongside the current value. We're using useEffect to update the prevCountRef with the current value of count after every render.

Referencing DOM Nodes

As mentioned earlier, useRef can be used to reference a DOM node. Let's see how this can be done:

import React, { useRef } from 'react';

function MyComponent() {
  const elementRef = useRef(null);

  function handleClick() {
    elementRef.current.style.color = 'red';
  }

  return (
    <div>
      <p ref={elementRef}>Hello, World!</p>
      <button onClick={handleClick}>Change Color</button>
    </div>
  );
}

In this example, we're using useRef to create a reference to the p element, and we're passing that reference to the ref prop of the p. When the handleClick function is called, it uses the current property of the elementRef to get a reference to the p element and change its color to red.

Conclusion

useRef is a powerful tool that can be used to reference DOM nodes and values between renders of a component. It's easy to use and can simplify our code by eliminating the need for some class components.