子组件
import { useImperativeHandle, forwardRef } from 'react';
export interface IRefProps {
hello: () => void;
}
type Props = {};
const Child= forwardRef<IRefProps, Props>((props, ref) => {
useImperativeHandle(
ref,
() => {
return {
hello: () => {
console.log('hello');
},
};
},
[]
);
return (
<></>
);
});
export default Child;
父组件
import { IRefProps } from '/preview/index';
const Father = () => {
const childRef = useRef<IRefProps>(null);
return(
<>
<Child ref={childRef} />
<button onClick={() => previewRef.current?.hello()} >触发子组件的hello方法</button>
</>
)
}