简体   繁体   中英

React: Access ref passed between components via render props

I would like to access a ref passed between two external components using render props ( real example ). Can it be done?

function Component() {
  // how to get access to `ref` here?

  return (
    <A>
      {({ref}) => (
        <B ref={ref}/>
      )}
    </A>
  )
}

You may need React.forwardRef

Ref forwarding is a technique for automatically passing a ref through a component to one of its children.

This is typically not necessary for most components in the application. However, it can be useful for some kinds of components, especially in reusable component libraries.

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

const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;

Figured it out. The ref render prop is actually badly named, it's not a ref but a function to set a ref, so we can just use a inline function (thought this may cause extra renders):

function Component() {
  const bRef = useRef(null);

  return (
    <A>
      {({ref: setRef}) => (
        <B ref={ref => {
          bRef.current = ref;
          setRef(ref);
        }}/>
      )}
    </A>
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM