显示键盘后滚动到FlatList的末尾

use*_*085 24 react-native

我在KeyboardAvoidingView中有一个FlatList.当键盘显示时,我想滚动到FlatList的末尾.

我正在侦听被触发的'keyboardDidShow'事件,但是由于FlatList在调用scrollToEnd后没有滚动到最后,因此可能会过早触发.

我已经查看了KeyboardAvoidingView的onLayout事件,但只是设置onLayout事件来触发一个函数似乎阻止了KeyboardAvoidingView在显示键盘时调整它的大小.

<KeyboardAvoidingView behavior='padding' style={{ flex: 1}} onLayout={this._scrollEnd}>
Run Code Online (Sandbox Code Playgroud)

码:

import React from 'react';
import {Image, Linking, Platform, ScrollView, StyleSheet, Text, TouchableOpacity, View, Button, Alert, FlatList, TextInput, KeyboardAvoidingView, Keyboard} from 'react-native';
import { MonoText } from '../components/StyledText';

export default class HomeScreen extends React.Component {
  constructor() {
    super();
    this.state = {
      messages: getMessages()
    };

    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._scrollEnd);
    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidHide', this._scrollEnd);
  }

  _scrollEnd = (evt) => {
    this.refs.flatList1.scrollToEnd();
  }

  render() {
    return (
      <KeyboardAvoidingView behavior='padding' style={{ flex: 1}} >
        <FlatList
          style={{ flex:1}}
          ref="flatList1"
          data={this.state.messages}
          renderItem={({ item }) => <Text>{item.text}</Text>}
        />
      </KeyboardAvoidingView>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Ant*_*met 38

我正在制作一个聊天组件,我想要同样的事情.它是这样的:

<FlatList
   ref={ref => this.flatList = ref}
   onContentSizeChange={() => this.flatList.scrollToEnd({animated: true})}
   onLayout={() => this.flatList.scrollToEnd({animated: true})}
   ...
/>
Run Code Online (Sandbox Code Playgroud)

键盘弹出会触发布局,因此已修复.到达的新聊天消息会触发内容更改,因此它也会滚动到底部(这是我想要的聊天窗口)

  • 兄弟的回答真棒! (2认同)

Kyo*_*agi 22

实际上,如果你总是想滚动到最后,意味着你总是希望看到最新的消息,我是对的吗?

然后使用新版本的react-native.并添加倒置以更改平面列表的倒置.

<FlatList
      inverted
      style={{ flex:1}}
      ref="flatList1"
      data={this.state.messages}
      renderItem={({ item }) => <Text>{item.text}</Text>}
    />
Run Code Online (Sandbox Code Playgroud)

然后重新安排你的this.state.messages倒置.那么你的最新消息将始终显示在平面列表的底部

对于我的情况,我不需要使用KeyboardAvoidingView

  • 很棒的想法,`倒置'就是我想要的 (3认同)

小智 7

一些用户 (@Nathileo) 要求使用基于钩子的方法来滚动到 FlatList 的末尾。

  1. 首先,您需要实现 React 的 useRef 钩子:

    import {useRef} from 'react';

    const yourRef = useRef(null);

  2. 其次,FlatList 标签必须配备引用和所需的功能:

    <FlatList
      ref={yourRef}
      onContentSizeChange={() => yourRef.current.scrollToEnd() }
      onLayout={() => yourRef.current.scrollToEnd() }
    />
    
    Run Code Online (Sandbox Code Playgroud)