简体   繁体   中英

Accessing refs of a sibling component in React

I have this situation where I have two sibling components, where the first component appears as follows:

class X extends Component {

   someRenderMethod(){
       //does something 
   }  

   render(){
      return(
          <div class="xyz">
             <p>some text</p>
             <div class="the-div-i-want-render" ref="one">
                   {this.someRenderMethod}
             </div>
          </div> 
      )
   }
}

function mapStateToProps(){
   //
}

function mapDispatchToProps(){
  //
}

export default connect(mapStateToProps, mapDispatchToProps)(X);

My second sibling component is as follows:

    import X from './x'

    export class Y extends Component {

       render(){
          return (
               <div>
                  <div>
                         //Here I want to render the div inside   //component X
                         // In the real case, I show the div here in                   //response to a button click event. 
                        //I have tried to import the component and get           //the refs of X, but that is not working. 
                  </div>

               </div>

           )
       }
    }

I have tried to import the component X into Y and get the refs of X, but that is not working (the ref object is always null). Is there any other way where I can accomplish this?

By importing X you are just importing the class for the component. Not the instance of it ( https://en.wikipedia.org/wiki/Class_(computer_programming) )

A components refs are not available until the component was mounted (rendered once). Therefore the first time you have access to the refs object is in the components componentDidMount life cycle function.

To address your problem: Component X needs to communicate its refs up the tree to a parent component. The parent renders both, X and Y . When X was mounted you can call a callback from your parent container passing the refs as an argument. The parent can now react to this and pass the refs object down to Y via props . You can make use of local state this.state/setState to easily achieve re-rendering of Y after X did mount.

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