繁体   English   中英

在React中访问同级组件的ref

[英]Accessing refs of a sibling component in React

在这种情况下,我有两个同级组件,第一个组件如下所示:

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);

我的第二个兄弟组件如下:

    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>

           )
       }
    }

我尝试将组件X导入Y并获取X的引用,但这不起作用(ref对象始终为null)。 还有其他方法可以实现这一目标吗?

通过导入X您只需导入组件的类。 不是它的实例( https://en.wikipedia.org/wiki/Class_(computer_programming)

在安装组件(渲染一次)之前,组件refs不可用。 因此,第一次访问refs对象是在组件componentDidMount生命周期函数中。

要解决您的问题:组件X需要将其对树的refs传达给父组件。 父级同时渲染XY 挂载X时,可以从父容器调用回调,并将refs作为参数传递。 父级现在可以对此做出反应,并将refs对象通过props传递给Y 您可以使用本地状态this.state/setState轻松完成X安装后对Y重新渲染。

暂无
暂无

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

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