And the parent component controls the child component’s input box to get focus

The parent component:

import React, { useRef, useEffect } from 'react'
import FancyInput from './FancyInput'

export default function Test() {
  const inputRef = useRef(null)
  const onButtonClick = () = > {
    inputRef.current.focus()
    inputRef.current.fun()
  }

  useEffect(() = > {
    inputRef.current.focus()
  }, [])
  return (
    <>
      <FancyInput ref={inputRef}></FancyInput>
      <button onClick={onButtonClick}>Focus the input</button>
    </>)}Copy the code

Child components:

import React, { useRef, useImperativeHandle, forwardRef } from 'react'

function FancyInput(props, ref) {
  const inputRef = useRef();
  useImperativeHandle(ref, () = > ({
    focus: () = > {
      inputRef.current.focus();
    },
    fun: () = > {
      console.log('Methods of child components')}}));return <input ref={inputRef} />;
}
FancyInput = forwardRef(FancyInput);

export default FancyInput
Copy the code