簡體   English   中英

React,如何訪問父級中的子級引用

[英]React, how to access child ref in parent

我正在嘗試訪問父母父母中的孩子 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>
}

我需要訪問 Home 組件(parent2)中的 ref,任何幫助將不勝感激。

將您的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

只要您不將其稱為ref ,您就可以像普通prop一樣傳遞ref

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM