【问题标题】:How to load more messages using react-native-gifted-chat, by scrolling up?如何通过向上滚动使用 react-native-gifted-chat 加载更多消息?
【发布时间】:2019-03-07 11:00:16
【问题描述】:

我想在滚动到顶部时加载更多消息。 有一个道具onLoadEarlier,我在这里传递了一个函数来加载更多消息,但它不起作用。打开聊天框时确实调用了这个函数,但我想在滚动到顶部时执行一个函数。

【问题讨论】:

    标签: react-native react-native-gifted-chat


    【解决方案1】:

    您可以在 listViewProps 中使用 scrollEventThrottleonScroll 属性来调用回调,当您在 GiftedChat 中点击 Scrollview 的顶部时。适合我。

    <GiftedChat
              messages={this.state.messages}
              listViewProps={{
                scrollEventThrottle: 400,
                onScroll: ({ nativeEvent }) => {
                  if (this.isCloseToTop(nativeEvent)) {
                    this.setState({refreshing: true});
                    this.loadMoreChat();
                  }
                }
              }}
              onSend={messages => this.onSend(messages)}
              user={{
                _id: 2,
              }}
            />
    
    isCloseToTop({ layoutMeasurement, contentOffset, contentSize }) {
        const paddingToTop = 80;
        return contentSize.height - layoutMeasurement.height - paddingToTop <= contentOffset.y;
      }
    

    代码参考取自here

    【讨论】:

      【解决方案2】:

      对于那些将inverted 设置为true 的人。
      listViewPropsscrollEventThrottleonScroll

      is_close_to_top({ layoutMeasurement, contentOffset, contentSize }) {
              return contentOffset.y <= 100; // 100px from top
      }
      
      [...]
      <GiftedChat
          messages={this.state.messages}
          inverted={true}
          listViewProps={{
              scrollEventThrottle: 400,
              onScroll: ({ nativeEvent }) => {
                  if (this.is_close_to_top(nativeEvent)) {
                      this.setState({is_loading: true}); // your state
                      this.load_earlier(); // your function
                  }
              }
          }}
          onSend={messages => this.send(messages)}
          user={{
              _id: 1
          }}
      />
      

      Based on NightFury's answer

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center