Focus text input box
.focus() Get the focus
When the user clicks the button, handleClick
the 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 handleClick
function named . This function is called when the button is clicked. Inside the function, we inputRef.current
get the DOM element pointed to by inputRef
the reference and call its focus
method to focus on the text input box.