gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:10:44 25 4
gpt4 key购买 nike

我正在尝试访问父项的父项中的子 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 并将其附加到 Child

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

return <Child parentRef={ref} />
}

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

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

Edit keen-sky-g9yxj

你可以像普通的 prop 一样传递一个 ref 只要你不调用它 ref

关于javascript - React,如何访问父级中的子引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58505450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com