面试题答案
一键面试基本步骤
- 在子组件中使用
useImperativeHandle
:- 导入
useImperativeHandle
和forwardRef
,forwardRef
用于将子组件的引用转发给父组件。 - 在子组件内部,
useImperativeHandle
接收三个参数:第一个是通过forwardRef
传递进来的ref
,第二个是一个函数,该函数返回要暴露给父组件的方法或属性,第三个是依赖项数组(类似于useEffect
的依赖项数组,可选)。
- 导入
- 在父组件中获取子组件引用并调用暴露的方法:
- 在父组件中创建一个
ref
对象,将其传递给子组件。 - 当需要调用子组件暴露的方法时,通过
ref.current
来访问这些方法。
- 在父组件中创建一个
简单示例
import React, { useImperativeHandle, forwardRef } from'react';
// 子组件
const ChildComponent = forwardRef((props, ref) => {
const handleChildMethod = () => {
console.log('子组件的方法被调用');
};
useImperativeHandle(ref, () => ({
callChildMethod: handleChildMethod
}));
return <div>子组件</div>;
});
// 父组件
const ParentComponent = () => {
const childRef = React.createRef();
const handleClick = () => {
if (childRef.current) {
childRef.current.callChildMethod();
}
};
return (
<div>
<ChildComponent ref={childRef} />
<button onClick={handleClick}>调用子组件方法</button>
</div>
);
};
export default ParentComponent;
在上述示例中,ChildComponent
通过forwardRef
和useImperativeHandle
暴露了callChildMethod
方法给父组件。父组件通过ref
获取子组件实例,并在按钮点击时调用子组件暴露的方法。