chunbin1 / blog

git actions + dumijs 写的博客
https://chunbin1.github.io/blog/
0 stars 0 forks source link

类型完整的React.forwardRef写法 #31

Open chunbin1 opened 2 years ago

chunbin1 commented 2 years ago

需求:一个评论用的窗口,通过forwardRef传递方法给父组件调用

export type CommentHandler = {
  openDrawer: () => void
  closeDrawer: () => void
}

const CommentDrawer: React.ForwardRefRenderFunction<CommentHandler, IProps> = (props,ref)=>{

 const openDrawer = ()=>{};
 const closeDrawer = ()=>{};
  useImperativeHandle(ref, () => {
    return {
      openDrawer,
      closeDrawer,
    }
  })
  return <div></div>
}

export default forwardRef(CommentDrawer)

使用

const ref = useRef<React.ElementRef<typeof CommentDrawer>>(null)
ref.current?.openDrawer()