简体   繁体   中英

Passing ref from parent to child component

I have a component ChatScroller for managing scrolling in a chat (autoscroll when new messages come in). This is a simplified version of it:

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

And it works as expected like this:

<ChatScroller>
   {messages.map(message => <ChatMessage message={message}/>}
</ChatScroller>

Now I have another component ScrollLoader for loading older messages as you scroll.

The problem is that it needs access to the same ref that ChatScroller uses so it can determine when to load more messages. I would like to do something like this:

<ChatScroller>
   <ScrollLoader handleLoad={this.handleLoad}>
      {messages.map(message => <ChatMessage message={message}/>}
   <ScrollLoader/>
</ChatScroller>

Any idea how I can access scrollRef from inside both components? Maybe I'm thinking about it all wrong but somehow both components need to have access to the scroll div..

Any help appreciated, thanks in advance (and sorry if my question is not clear)

solved it by doing like this:

<ChatScroller scrollRef={this.scrollRef}>
   <ScrollLoader handleLoad={this.handleLoad} scrollRef={this.scrollRef}>
      <div ref={this.scrollRef}>
         {messages.map(message => <ChatMessage message={message}/>}
      <div>
   <ScrollLoader/>
</ChatScroller>

... still not sure this is the right way but it works.

Leaving this up for any better solutions, cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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