[英]Passing a Ref from a Child to a Parent in React with Class Component
[英]Passing ref from parent to child component
我有一個ChatScroller
組件,用於管理聊天中的滾動( ChatScroller
時自動滾動)。 這是它的簡化版本:
class ChatScroller extends Component {
scrollRef = node => this.scrollNode = node
componentDidUpdate() {
this.scrollNode.scrollTop = this.scrollNode.scrollHeight
}
render() {
return (
<div style={{...this.props.style, overflowY: 'scroll'}} ref={this.scrollRef}>
{this.props.children}
</div>
)
}
}
它按預期工作,如下所示:
<ChatScroller>
{messages.map(message => <ChatMessage message={message}/>}
</ChatScroller>
現在,我還有另一個組件ScrollLoader
用於在滾動時加載較舊的消息。
問題在於,它需要訪問ChatScroller
使用的相同引用,以便可以確定何時加載更多消息。 我想做這樣的事情:
<ChatScroller>
<ScrollLoader handleLoad={this.handleLoad}>
{messages.map(message => <ChatMessage message={message}/>}
<ScrollLoader/>
</ChatScroller>
知道如何從兩個組件內部訪問scrollRef
嗎? 也許我在想這一切都是錯誤的,但是無論如何,兩個組件都需要訪問滾動div。
任何幫助表示贊賞,在此先感謝(如果我的問題不清楚,請多謝)
通過這樣來解決它:
<ChatScroller scrollRef={this.scrollRef}>
<ScrollLoader handleLoad={this.handleLoad} scrollRef={this.scrollRef}>
<div ref={this.scrollRef}>
{messages.map(message => <ChatMessage message={message}/>}
<div>
<ScrollLoader/>
</ChatScroller>
...仍然不確定這是正確的方法,但它是否有效。
留下任何更好的解決方案,加油!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.