How does ref in React operate dom nodes to make the input box focus

Focus text input box

.focus() Get the focus

insert image description here

When the user clicks the button, handleClickthe function is called to focus the text input.

// 焦文字输入框
import {
    
     useRef } from "react";

const FocusForm = () => {
    
    
  const inputRef = useRef<any>(null);

  function handleClick() {
    
    
    // 获取输入框焦点
    inputRef.current.focus();
  }

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

export default FocusForm;

Define a handleClickfunction named . This function is called when the button is clicked. Inside the function, we inputRef.currentget the DOM element pointed to by inputRefthe reference and call its focusmethod to focus on the text input box.

Guess you like

Origin blog.csdn.net/wbskb/article/details/132655364