在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作为道具传递时,还可以使用ImperitaveHandle Hook吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)