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

前端 未结 16 1263
误落风尘
误落风尘 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:41

    Here is the simplest solution I could muster:

     <ListView
    ref={ref => (this.listView = ref)}
    onLayout={event => {
        this.listViewHeight = event.nativeEvent.layout.height;
    }}
    onContentSizeChange={() => {
        this.listView.scrollTo({
            y: this.listView.getMetrics().contentLength - this.listViewHeight
        });
    }}
    />;
    
    0 讨论(0)
  • 2020-12-04 17:43

    Use onContentSizeChange to keep track of the bottom Y of the scroll view (height)

    https://facebook.github.io/react-native/docs/scrollview.html#oncontentsizechange

    var _scrollToBottomY
    
    <ScrollView
        onContentSizeChange={(contentWidth, contentHeight)=>{
        _scrollToBottomY = contentHeight;
        }}>
    </ScrollView>
    

    then use the ref name of the scroll view like

    this.refs.scrollView.scrollTo(_scrollToBottomY);
    
    0 讨论(0)
  • 2020-12-04 17:48

    For React Native 0.41 and later, you can do this with the built-in scrollToEnd method:

    <ScrollView
        ref={ref => {this.scrollView = ref}}
        onContentSizeChange={() => this.scrollView.scrollToEnd({animated: true})}>
    </ScrollView>
    
    0 讨论(0)
  • 2020-12-04 17:48

    In case anyone in 2020 or later is wondering how to achieve this with functional components. This is how I did:

    ref={ref => scrollView = ref }
    onContentSizeChange={() => scrollView.scrollToEnd({ animated: true })}>
    
    0 讨论(0)
  • 2020-12-04 17:48

    A bit late... but look at this question. Scroll to top of ScrollView

    ScrollView has a "scrollTo" method.

    0 讨论(0)
  • 2020-12-04 17:49

    If you use TypeScript You need to do this

    interface Props extends TextInputProps { 
         scrollRef?: any;
    }
    
    export class Input extends React.Component<Props, any> {
         scrollRef;
    constructor(props) {
        this.scrollRef = React.createRef();
    }
    <ScrollView
        ref={ref => (this.scrollRef = ref)}
        onContentSizeChange={() => {
        this.scrollRef.scrollToEnd();
        }}
    >
    </ScrollView>
    
    0 讨论(0)
提交回复
热议问题