父组件引入useRef
javascript
import { useState, useEffect, useContext, useRef } from 'react';
const sonRef = useRef(null)
html
return (
<div>
<Son ref={sonRef} onClick={handleClickO} count={count}></Son>
</div>
);
function handleClickO(e) {
console.log(e, 'eeeeeeeeeeeeee');
console.log(sonRef, 'sonRef');
}
子组件触发
javascript
import { useImperativeHandle, forwardRef } from "react";
function Son(params, ref) {
const childFunction = () => {
console.log('子组件函数被调用');
};
// 将子组件的函数暴露给父组件通过 ref 获取
useImperativeHandle(ref, () => ({
childFunction,
}));
return (
<div>
{params.count}
<button>
Clicked {count} Son times
</button>
</div>
)
}
export default forwardRef(Son);