text
Autofocus can make your application more user-friendly, and there are several ways to automatically focus the React input box.
The easiest way to make the input box automatically focus is to useautoFocus
Properties (note case):
<input name="username" type="text" autoFocus />
Since this property works inconsistently in different browsers, React implements a polyfill internally, which will be used when the element is mounted.focus()
method.
But this is not always useful, we need to encapsulate one ourselves.
There are two ways to implement it:
- use
useCallback()
- use
useRef()
anduseEffect()
We'll write it into a Hooks so that we can reuse it in the project.
Use useCallback()
useCallback()
The hook returns a memorized callback function. It accepts two parameters. The first is the function to be run, and the second is the array of values that the function depends on.
import { useCallback } from 'react' const useAutoFocus = () => { const inputRef = useCallback((inputElement) => { if (inputElement) { () } }, []) return inputRef } export default useAutoFocus
NoteduseCallback
The second parameter of is an empty array, which means that the function only runs once when the component is rendered.
When the form component renders, a reference to the input box is set. It executesuseCallback()
Function in the hook, which calls the input boxfocus()
。
Use useRef() and useEffect()
useffect()
The hook will tell React that after the component renders, you need the component to perform some operations. It accepts two parameters. The first is the function to be run, and the second is an array of dependencies, whose functions are asuseCallback()
The same in .
useRef()
The role of hooks on function components andcreateRef()
The same effect on class-based components. This hook creates a plain JavaScript object that you can pass to an element to keep a reference to it. Can be passed through the objectcurrent
Attributes access this reference.
import { useRef, useEffect } from 'react' const useAutoFocus = () => { const inputRef = useRef(null) useEffect(() => { if () { () } }, []) return inputRef } export default useAutoFocus
In the above code, we create a reference to the input box. Then, when the component renders, we use the reference object'scurrent
The property call input boxfocus()
。
Example of usage
import { useState, useEffect } from 'react' import ReactDOM from 'react-dom' import useAutoFocus from './hooks/useAutoFocus' function App() { const emailInput = useAutoFocus() return ( <> <form> <label> user <input name='username' type='text' ref={emailInput} /> </label> <label> password <input name='password' type='password' /> </label> <button type='submit'>Log in</button> </form> </> ) } (<App />, ('root'))
More information
React Hooks
The above is the detailed explanation of the use of React autofocus fields. For more information about React autofocus fields, please follow my other related articles!