0
点赞
收藏
分享

微信扫一扫

react-hooks父组件调用子组件方法

勇敢乌龟 2022-05-03 阅读 66
import React, { forwardRef, useImperativeHandle } from 'react'
import { Button } from 'antd'
export default function Category() {
  const domRef = React.useRef()
  const handleClick = () => {
    // @ts-ignore
    domRef.current.handleClick()
  }
  return (
    <div style={{}}>
      Category
      <Button type="primary" onClick={handleClick}>
        父组件的按钮
      </Button>
      <div
        style={{
          marginTop: '20px',
          width: '200px',
          height: '200px',
          border: '1px solid red',
        }}
      >
        <Child ref={domRef}>这是子组件...</Child>
      </div>
    </div>
  )
}
// 实现一个组件的引用

export const Child = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    handleClick,
  }))
  const handleClick = () => {
    console.log('子组件的按钮被点击了')
  }
  // @ts-ignore
  return <div>{props.children}</div>
})

举报

相关推荐

0 条评论