[英]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
傳達給父組件。 父級同時渲染X
和Y
掛載X
時,可以從父容器調用回調,並將refs
作為參數傳遞。 父級現在可以對此做出反應,並將refs
對象通過props
傳遞給Y
您可以使用本地狀態this.state/setState
輕松完成X
安裝后對Y
重新渲染。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.