首页 > 解决方案 > 在 React 中使用 forwardRef 或仅将 ref 作为 prop 传递之间的区别及其对 useImperitaveHandle 的影响

问题描述

React 文档为 forwardRef 提供了以下示例

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;

但是当 ref 作为 prop 传递而不是通过 ForwardRef 传递时,这段代码也可以工作

const FancyButton = (props) => (
  <button ref={props.testRef} className="FancyButton">
    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton testRef={ref}>Click me!</FancyButton>;

如果两者的工作方式相同,那么使用 ForwardRef 的原因是什么?

当 ref 作为道具传递时,也可以使用 useImperitaveHandle Hook 吗?

标签: reactjsreact-hooksreact-ref

解决方案


推荐阅读