簡體   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