React Hooks之useState、useRef

React Hooks are a new feature introduced in React 16.8 that allow us to use state and other React features in functional components without writing class components. Two of the commonly used React Hooks are useState and useRef.

useState is a function used to declare and manage state in functional components. It accepts an initial state value as a parameter and returns an array containing the current state value and the updated state value. By destructuring assignments, we can easily get and update state.

For example, we can use useState in a function component to create a counter:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

In the above example, we use useState to declare a state called count and set its initial value to 0. We also declare a function called setCount to update the count status. When the button is clicked, we call the increment function to increase the count status value by 1, and update the count value through the setCount function.

useRef is another React Hook that allows us to create mutable references in functional components. useRef returns a mutable ref object that remains unchanged throughout the lifetime of the component.

A common use case is to bind a ref object to a DOM element in order to access the DOM element's properties and methods when necessary.

For example, we can use useRef to get the value of the input box:

import React, { useRef } from 'react';

function Input() {
  const inputRef = useRef();

  const handleButtonClick = () => {
    alert(inputRef.current.value);
  };

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={handleButtonClick}>Show Value</button>
    </div>
  );
}

In the above example, we created a reference named inputRef using useRef. We then pass the inputRef reference to the text input box's ref attribute to associate the DOM node with the inputRef.

When the button is clicked, we get the value of the input box through inputRef.current.value and display it through the alert function. Since inputRef is a mutable object, it can maintain its state throughout the component's life cycle and will not change as the component is re-rendered.

To summarize, useState allows us to declare and manage state in function components, while useRef allows us to create mutable references in function components. These two React Hooks provide us with a more convenient and flexible way to handle state and DOM operations.

Guess you like

Origin blog.csdn.net/m0_74801194/article/details/135400768