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

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>
})

你可能感兴趣的:(学习,学习打卡,笔记,react.js,javascript,前端)