简体   繁体   中英

Targeting/Scrolling to a React Component that is not a close parent/child

I have a situation where I want to scroll to a React component from another component that is not in a direct or close parent/child relationship.

The structure can be explained as follows:

Component A > a parent > a parent > a parent > a parent > a parent > a parent > a child > a child > Component B

As you can see it is not direct at all. If the relationship were direct, or even a grandparent/grandchild, I would usually pass a ref. However in this instance, I would need to pass the ref through 10 or so files in order to have access to it, which seems ridiculous.

I know I can use document.getElementById (or similar) but was wondering if there is a way I can do this via a ref or something similar in React?

You may try React Context . Put the Context Provider in Component A, and Context Consumer in Component B. B the can pass its ref to A via the Context, or vice versa

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