value of using React.forwardRef vs custom ref prop

后端 未结 2 1740
终归单人心
终归单人心 2020-12-05 02:23

I see that React.forwardRef seems to be the sanctioned way of passing a ref to a child functional component, from the react docs:

const FancyButton = React.f         


        
相关标签:
2条回答
  • 2020-12-05 02:40

    Even React docs mention the custom ref prop as a more flexible approach to forwardRef:

    If you use React 16.2 or lower, or if you need more flexibility than provided by ref forwarding, you can use this alternative approach and explicitly pass a ref as a differently named prop.

    There is also a gist, in which Dan Abramov writes about its advantages:

    • compatible with all React versions
    • works for class and function components
    • simplifies passing a ref to a nested component several layers deep

    I would add, that passing refs as usual props does not cause breaking changes and is the way to go for multiple refs. The only advantages of forwardRef coming to my mind are:

    • uniform access API for DOM nodes, functional and class components (you mentioned that)
    • ref attribute does not bloat your props API, e.g. if you provide types with TypeScript

    Does passing a custom prop affect diffing when it comes to rendering and cause additional renders?

    A ref can potentially trigger a re-render if you pass an inline callback ref function down as prop. But it is a better idea anyway to define it as class instance method or via some memoization like useCallback.

    0 讨论(0)
  • 2020-12-05 02:50

    Ref is a standard property in React components.

    Some components that wrap other components to provide additional functionality, use ref to refer to wrapped component and expect that the component has ref property.

    It is better for a component to have the ref property to be compatible with other components and libraries.

    Function components cannot have the "ref" property and must use forwardRef instead to provide ref property.

    0 讨论(0)
提交回复
热议问题