简体   繁体   English

在React中访问同级组件的ref

[英]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). 我尝试将组件X导入Y并获取X的引用,但这不起作用(ref对象始终为null)。 Is there any other way where I can accomplish this? 还有其他方法可以实现这一目标吗?

By importing X you are just importing the class for the component. 通过导入X您只需导入组件的类。 Not the instance of it ( https://en.wikipedia.org/wiki/Class_(computer_programming) ) 不是它的实例( https://en.wikipedia.org/wiki/Class_(computer_programming)

A components refs are not available until the component was mounted (rendered once). 在安装组件(渲染一次)之前,组件refs不可用。 Therefore the first time you have access to the refs object is in the components componentDidMount life cycle function. 因此,第一次访问refs对象是在组件componentDidMount生命周期函数中。

To address your problem: Component X needs to communicate its refs up the tree to a parent component. 要解决您的问题:组件X需要将其对树的refs传达给父组件。 The parent renders both, X and Y . 父级同时渲染XY When X was mounted you can call a callback from your parent container passing the refs as an argument. 挂载X时,可以从父容器调用回调,并将refs作为参数传递。 The parent can now react to this and pass the refs object down to Y via props . 父级现在可以对此做出反应,并将refs对象通过props传递给Y You can make use of local state this.state/setState to easily achieve re-rendering of Y after X did mount. 您可以使用本地状态this.state/setState轻松完成X安装后对Y重新渲染。

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

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