面试题答案
一键面试useImperativeHandle钩子的作用
useImperativeHandle
钩子用于在使用 ref
时自定义暴露给父组件的实例值。通常情况下,React 鼓励通过 props 进行父子组件通信,但在某些场景下,父组件可能需要直接访问子组件的某些方法或属性,useImperativeHandle
可以让我们控制这种暴露的行为,避免直接暴露整个子组件实例,从而保持组件的封装性。
父子组件通信中使用示例
- 创建子组件
在上述代码中,import React, { useImperativeHandle, forwardRef } from 'react'; const ChildComponent = forwardRef((props, ref) => { const customMethod = () => { return "这是子组件的自定义方法返回值"; }; useImperativeHandle(ref, () => ({ customMethod: customMethod })); return <div>子组件内容</div>; }); export default ChildComponent;
forwardRef
用于将ref
转发到子组件内部。useImperativeHandle
定义了通过ref
暴露给父组件的内容,这里只暴露了customMethod
方法。 - 在父组件中使用子组件
在父组件中,通过import React, { useRef } from'react'; import ChildComponent from './ChildComponent'; const ParentComponent = () => { const childRef = useRef(); const callChildMethod = () => { if (childRef.current) { const result = childRef.current.customMethod(); console.log(result); } }; return ( <div> <ChildComponent ref={childRef} /> <button onClick={callChildMethod}>调用子组件方法</button> </div> ); }; export default ParentComponent;
useRef
创建一个ref
并传递给子组件。当点击按钮时,通过ref
调用子组件暴露的customMethod
方法。