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

前端 未结 5 1720
灰色年华
灰色年华 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:15

    Incase you need to reuse this in many difference components, you can export this ability to something like withForwardingRef

    const withForwardingRef = (BaseComponent: React.ReactType) =>
        React.forwardRef((props, ref) => );
    
    export default withForwardingRef;
    

    usage:

    const Comp = ({forwardedRef}) => (
     
    )
    const EnhanceComponent = withForwardingRef(Comp);  // Now Comp has a prop called forwardedRef
    

提交回复
热议问题