以及父组件控制子组件的input框获取焦点
父组件:
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>
</>
)
}
子组件:
import React, { useRef, useImperativeHandle, forwardRef } from 'react'
function FancyInput(props, ref) {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
},
fun: () => {
console.log('子组件的方法')
}
}));
return <input ref={inputRef} />;
}
FancyInput = forwardRef(FancyInput);
export default FancyInput