面试官:forwardRef 怎么使用?
参考链接:《深入理解react》之memo、forwardRef原理
forwardRef
是 React 提供的一种特殊的高阶组件(Higher Order Component),用于在函数组件中向子组件传递 ref。
在 React 中,函数组件默认不支持 ref
属性,这意味着无法直接通过 ref
属性获取函数组件的实例。但有时候我们希望能够在父组件中通过 ref
获取到子组件的实例,这时就可以使用 forwardRef
。
使用 forwardRef
可以在函数组件中传递 ref
,使得父组件可以直接访问子组件的 DOM 元素或实例。
以下是 forwardRef
的基本使用方法:
import React, { forwardRef } from 'react';
const ChildComponent = forwardRef((props, ref) => {
return <input ref={ref} />;
});
const ParentComponent = () => {
const inputRef = React.useRef(null);
const handleClick = () => {
inputRef.current.focus();
};
return (
<div>
<ChildComponent ref={inputRef} />
<button onClick={handleClick}>Focus Input</button>
</div>
);
};
在上面的示例中,ChildComponent
是一个函数组件,通过 forwardRef
包裹后,可以接受 ref
参数。父组件 ParentComponent
使用 ref
将 inputRef
传递给 ChildComponent
,从而实现在父组件中通过 inputRef.current
访问子组件的 DOM 元素。
版权申明
本文系作者 @K 原创发布在前端面试题大全站点。未经许可,禁止转载。
暂无评论数据