React源码解析(五):forward-ref

作用:因为react中Function Component是没有实例的,没有办法进行传递ref。所以,就产生了React.forwardRef这个API来解决这个问题。

export default function forwardRef$ElementType>(  
    render: (props: Props, ref: React$Ref) => React$Node,
) {  
    if (__DEV__) { ...}  

    return {    
        $$typeof: REACT_FORWARD_REF_TYPE,    
        render,  
    };
}复制代码

使用方法:

const FancyButton = React.forwardRef((props, ref) => (
  
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
Click me!;复制代码

HOC下:

function logProps(Component) {
  class LogProps extends React.Component {
    componentDidUpdate(prevProps) {
      console.log('old props:', prevProps);
      console.log('new props:', this.props);
    }

    render() {
      const {forwardedRef, ...rest} = this.props;

      // Assign the custom prop "forwardedRef" as a ref
      return ;
    }
  }

  // Note the second param "ref" provided by React.forwardRef.
  // We can pass it along to LogProps as a regular prop, e.g. "forwardedRef"
  // And it can then be attached to the Component.
  return React.forwardRef((props, ref) => {
    return ;
  });
}复制代码


你可能感兴趣的:(javascript)