直接上代码
import React, { useRef } from 'react';
const MyComponent = () => {
const myComponentRef = useRef(null);
const handleClick = () => {
myComponentRef.current.myMethod();
};
return (
<div>
<button onClick={handleClick}>调用组件方法</button>
<ChildComponent ref={myComponentRef} />
</div>
);
};
const ChildComponent = React.forwardRef((props, ref) => {
const myMethod = () => {
console.log('调用了组件方法');
};
React.useImperativeHandle(ref, () => ({
myMethod,
}));
return <div>子组件</div>;
});
export default MyComponent;