使用 React.forwardRef 与自定义 ref prop 的价值

Les*_*baa 74 javascript performance reactjs

我看到 React.forwardRef 似乎是将 ref 传递给子功能组件的认可方式,来自 react 文档:

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>;
Run Code Online (Sandbox Code Playgroud)

但是,与简单地传递自定义道具相比,这样做有什么优势?:

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

const ref = React.createRef();
<FancyButton innerRef={ref}>Click me!</FancyButton>;
Run Code Online (Sandbox Code Playgroud)

我能想到的唯一优势可能是为 refs 提供了一致的 api,但还有其他优势吗?传递自定义道具是否会影响渲染时的差异并导致额外的渲染,肯定不会因为 ref 在current字段中存储为可变状态?

例如,假设您想传递多个 refs(这可能表明代码异味,但仍然如此),那么我能看到的唯一解决方案是使用 customRef 道具。

我想我的问题是使用forwardRef自定义道具的价值是什么?

for*_*d04 59

甚至React 文档也提到自定义 ref prop 是一种更灵活的方法forwardRef

如果您使用 React 16.2 或更低版本,或者如果您需要比 ref forwarding 提供的更多灵活性,您可以使用这种替代方法并将ref 作为不同命名的 prop显式传递。

还有一个要点,其中丹·阿布拉莫夫 (Dan Abramov) 写到了它的优点:

  • 兼容所有 React 版本
  • 适用于类和函数组件
  • 简化将 ref 传递给多层深的嵌套组件

我要补充的是,像往常一样传递 refs 不会导致破坏性更改,并且是多个 refs 的方法。forwardRef我想到的唯一优点是:

  • DOM 节点、功能和类组件的统一访问 API(您提到过)
  • ref 属性不会使您的道具 API 膨胀,例如,如果您使用 TypeScript 提供类型

传递自定义道具是否会影响渲染并导致额外渲染?

如果您将内联回调 ref函数作为 prop 向下传递,则 ref 可能会触发重新渲染。但它是一个更好的主意,反正它定义为类的实例方法,或通过像一些记忆化useCallback

  • 优势点还不足以成为引入整个 API 的理由,恕我直言,只是代码膨胀 (3认同)