useImperativeHandle

531 阅读1分钟
  • 回顾ref,forwardRef的使用
    • 通过forwardRef可以将ref转发到子组件
    • 子组件拿到父组件创建的ref,绑定到自己的某-个元素中
  • forwardRef使用带来的问题
    • 直接暴露给父组件,使的某些情况不可控
    • 父组件拿到子组件后可以进行任意的操作
  • 通过useImperativeHandle可以暴露固定的操作
    • 通过useImperativeHandle的Hook,将传入的ref和useImperativeHandle第二个参数返回的对象绑定到一起

案列


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

const HYInput = forwardRef((props,ref)=> {
  return <input ref={ref} type="text"/>
})



export default function UseImperativeHandleHookDemo() {

  const inputRef = useRef() 

  return (
    <div>
      <HYInput ref={inputRef}/>
      <button onClick={e=>inputRef.current.focus()}>聚焦</button>
    </div>
  )

}

案列二


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

const HYInput = forwardRef((props,ref)=> {
  const inputRef = useRef()
  useImperativeHandle(ref,()=> {
    return {
      focus: () => {
        console.log(345);
        inputRef.current.focus()
      }
    } 
  })

  return <input ref={inputRef} type="text"/>
})
export default function UseImperativeHandleHookDemo() {
  const inputRef = useRef()
  return (
    <div>
      <HYInput ref={inputRef}/>
      <button onClick={e=>inputRef.current.focus()}>聚焦</button>
    </div>
  )
}