简体   繁体   English

将引用从父级传递到子级组件

[英]Passing ref from parent to child component

I have a component ChatScroller for managing scrolling in a chat (autoscroll when new messages come in). 我有一个ChatScroller组件,用于管理聊天中的滚动( ChatScroller时自动滚动)。 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. 现在,我还有另一个组件ScrollLoader用于在滚动时加载较旧的消息。

The problem is that it needs access to the same ref that ChatScroller uses so it can determine when to load more messages. 问题在于,它需要访问ChatScroller使用的相同引用,以便可以确定何时加载更多消息。 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? 知道如何从两个组件内部访问scrollRef吗? Maybe I'm thinking about it all wrong but somehow both components need to have access to the scroll div.. 也许我在想这一切都是错误的,但是无论如何,两个组件都需要访问滚动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! 留下任何更好的解决方案,加油!

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

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