子组件使用forwardRef和useImperativeHandle,父组件直接通过ref调用,代码如下
子组件
import { forwardRef, useImperativeHandle } from "react";
const Child = forwardRef((props, ref) => {
const aMethod = () => {
alert("这是一个子组件方法");
};
const bMethod = () => {
alert("这是子组件方法2");
};
useImperativeHandle(ref, () => ({
aMethod,
bMethod,
}));
return <div>子组件内容</div>;
});
export default Child;
父组件
import { useRef } from "react";
import Child from "./Child";
export default function Parent() {
const childRef = useRef();
const handleClick=()=>{
childRef.current.aMethod();
}
return (
<div>
<Child ref={childRef} />
<button onClick={handleClick}>点击调用子组件方法</button>
</div>
);
}