How to use React.forwardRef in a class based component?

前端 未结 5 1719
灰色年华
灰色年华 2020-12-04 10:37

I\'m trying to use React.forwardRef, but tripping over how to get it to work in a class based component (not HOC).

The docs examples use elements and functional comp

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 11:11

    This can be accomplished with a higher-order component, if you like:

    import React, { forwardRef } from 'react'
    
    const withForwardedRef = Comp => {
      const handle = (props, ref) =>
        
    
      const name = Comp.displayName || Comp.name
      handle.displayName = `withForwardedRef(${name})`
    
      return forwardRef(handle)
    }
    
    export default withForwardedRef
    

    And then in your component file:

    class Boop extends React.Component {
      render() {
        const { forwardedRef } = this.props
    
        return (
          
    ) } } export default withForwardedRef(Boop)

    I did the work upfront with tests & published a package for this, react-with-forwarded-ref: https://www.npmjs.com/package/react-with-forwarded-ref

提交回复
热议问题