day10-03.forwardRef + useImperativeHandle
forwardRef
作用:允许组件使用ref将一个DOM节点暴露给父组件
import { forwardRef, useRef } from 'react'
const MyInput = forwardRef(function Input(props, ref) {
return <input {...props} type="text" ref={ref} />
}, [])
function App() {
const ref = useRef(null)
const focusHandle = () => {
console.log(ref.current.focus())
}
return (
<div>
<MyInput ref={ref} />
<button onClick={focusHandle}>focus</button>
</div>
)
}
export default AppuseImperativeHandle
作用:如果我们并不想暴露子组件中的DOM而是想暴露子组件内部的方法
Last updated
Was this helpful?