Is it possible to keep a ScrollView scrolled to the bottom?

前端 未结 16 1264
误落风尘
误落风尘 2020-12-04 17:13

For a chat-like app, I want to keep a ScrollView component scrolled to the bottom, because newest messages appear under the older ones. Can we adjust the scroll

相关标签:
16条回答
  • 2020-12-04 17:58

    I had a similar problem, but after reading this page (which give me a headache!) I find this very nice npm package which just invert the ListView and make everything easy for a chat application!!

    0 讨论(0)
  • 2020-12-04 18:01

    This answers your question: https://stackoverflow.com/a/39563100/1917250

    You need to keep constantly scrolling to the bottom of the page by calculating the height of the content minus the height of its scrollView.

    0 讨论(0)
  • 2020-12-04 18:02

    For anyone writing function component that can use hook,

    import React, { useRef } from 'react';
    import { ScrollView } from 'react-native';
    
    const ScreenComponent = (props) => {
      const scrollViewRef = useRef();
      return (
        <ScrollView
          ref={scrollViewRef}
          onContentSizeChange={() => scrollViewRef.current.scrollToEnd({ animated: true })}
        />
      );
    };
    
    0 讨论(0)
  • 2020-12-04 18:04

    You can invert the scroll/list view using the react-native-invertible-scroll-view module, then simply call ref.scrollTo(0) to scroll to bottom.

    Install the module:

    npm install --save react-native-invertible-scroll-view
    

    Then import the component:

    import InvertibleScrollView from 'react-native-invertible-scroll-view';
    

    Then use the following JSX instead of a ScrollView:

    <InvertibleScrollView inverted
        ref={ref => { this.scrollView = ref; }}
        onContentSizeChange={() => {
            this.scrollView.scrollTo({y: 0, animated: true});
        }}
    >
        { /* content */ }
    </InvertibleScrollView>
    

    This works because react-native-invertible-scroll-view flips the entire view's content. Note that the view's children will also render in the opposite order to a normal view - the first child will appear at the bottom.

    0 讨论(0)
提交回复
热议问题