子组件通过useImperativeHandle
抛出方法
import React, { forwardRef, useImperativeHandle } from 'react'
import { Button } from 'antd'
export default function Category() {
const domRef = React.useRef()
const handleClick = () => {
domRef.current.handleClick()
}
return (
<div style={{}}>
Category
<Button type="primary" onClick={handleClick}>
父组件的按钮
</Button>
<Child ref={domRef}>这是子组件...</Child>
</div>
)
}
export const Child = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
handleClick,
}))
const handleClick = () => {
console.log('子组件的按钮被点击了')
}
return <div>{props.children}</div>
})