在React函数组件中,可以使用 useRef
hook 来创建一个引用对象,并将其传递给子组件。下面是一个简单的示例:
import { useRef } from 'react';
function ParentComponent() {
const childRef = useRef(null);
const handleClick = () => {
childRef.current.doSomething(); // 调用子组件的方法
};
return (
<>
<ChildComponent ref={childRef} />
<button onClick={handleClick}>调用子组件方法</button>
</>
);
}
const ChildComponent = React.forwardRef((props, ref) => {
const doSomething = () => {
console.log('子组件被调用了');
};
// 将ref与子组件关联起来
React.useImperativeHandle(ref, () => ({
doSomething,
}));
return <div>子组件</div>;
});
在该示例中,父组件 ParentComponent
创建了一个 childRef
引用对象,并将其作为 ref
属性传递给子组件 ChildComponent
。ChildComponent
使用 forwardRef
方法包裹函数组件,并在其中定义了一个 doSomething
方法。使用 useImperativeHandle
hook 可以将 ref
对象与子组件实例关联起来,并暴露出一个 doSomething
方法。
最后,在父组件中,我们可以通过 childRef.current.doSomething()
来调用子组件的 doSomething
方法。