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

时间:2018-10-25 23:27:40

标签: javascript reactjs scroll chat

我有一个public ParticleSystem particleSystem; private bool isPlaying = false; void Start() { particleSystem = GetComponent<ParticleSystem>(); particleSystem.Clear(); // Reset the particles } void Update() { if(!isPlaying) { particleSystem.Play(); isPlaying = true; } } 组件,用于管理聊天中的滚动(收到新消息时自动滚动)。这是它的简化版本:

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> 吗?也许我在想这都是错误的,但是无论如何,两个组件都需要访问滚动div。

任何帮助表示感谢,在此先感谢(如果我的问题不清楚,请多谢)

1 个答案:

答案 0 :(得分:0)

通过以下操作解决了该问题:

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

...仍然不确定这是正确的方法,但是它是否有效。

留下任何更好的解决方案,加油!

相关问题