简体   繁体   English

React,如何访问父级中的子级引用

[英]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,我正在尝试访问父母父母中的孩子 Ref,我似乎无法弄清楚,有谁知道我该如何实现这一点,

// 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.我需要访问 Home 组件(parent2)中的 ref,任何帮助将不胜感激。

Lift your ref to Parent and append it inside Child将您的ref提升到Parent和 append 它在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只要您不将其称为ref ,您就可以像普通prop一样传递ref

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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