简体   繁体   中英

React, how to access child ref in parent

I'm trying to access a child Ref in the parent's parent, I don't seem to be able to figure it out, does anyone know how I can achieve this,

// Child
const RightMenu = ({t}) => {

  const juraLiveIconRef = useRef();

  return (
     <Row className="pt-4">
        <Col>
          <img
            ref={juraLiveIconRef}
            src={require("../../assets/jura-live-grey.png")}
          />
        </Col>
     </Row>
  )
}

 //Parent1
const BottomMenu = ({ t}) => {

   <div className="bottom-menu-right-menu">
      <RightMenu />
   </div>

}

 //Parent2
const Home = ({ t }) => {

   <div>
    <BottomMenu />
   </div>
}

I need to access the ref in Home component(parent2), any help would be appreciated.

Lift your ref to Parent and append it inside Child

const Parent = () =>{
    const ref = useRef(null)

    return <Child parentRef={ref} />
}

const Child = props => <GrandChild {...props}/>

const GrandChild = ({ parentRef }) => <div ref={parentRef} />

编辑敏锐天空-g9yxj

You can pass a ref down like a normal prop as long as you don't call it ref

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