代码之家  ›  专栏  ›  技术社区  ›  Yash Vaghela

在ScrollView中自动滚动

  •  2
  • Yash Vaghela  · 技术社区  · 8 年前

    我正在创建聊天应用程序,并希望在中自动滚动到底部 ScrollView 每次收到新消息时。

    这是我的代码:

    <ScrollView>
      <FlatList
        data={this.state.dataSource}
        renderItem={({ item }) => <SenderChatRow data={item} />}
        keyExtractor={(item, index) => index}
      />
      {this._bookingRequestMessage()}
    </ScrollView>
    
    2 回复  |  直到 8 年前
        1
  •  12
  •   MoKhajavi75    8 年前

    在React Native 0.41及更高版本中,您可以使用:

    <ScrollView
        ref={ref => this.scrollView = ref}
        onContentSizeChange={(contentWidth, contentHeight)=>{        
            this.scrollView.scrollToEnd({animated: true});
        }}>
    </ScrollView>
    

    看看 Docs

    使现代化

    正如你提到的,键盘打开时出现问题,首先:

    import { Keyboard } from "react-native";

    componentDidMount() :

    componentDidMount() {
      this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', 
        this._keyboardDidShow.bind(this));
    }
    
    
    componentWillUnmount() {
      this.keyboardDidShowListener.remove();
      this.keyboardDidHideListener.remove();
    }
    
    _keyboardDidShow() {
      this.scrollView.scrollToEnd({ animated: false })
    }
    

    谢谢 chetan godiya 更新!

        2
  •  0
  •   chetan godiya    8 年前

    用于scrollview 将这些行添加到滚动视图中

    <ScrollView
                ref={(ref) => this.flatListRef = ref}
                contentContainerStyle={{ flex: 1 }}
                onContentSizeChange={(width, height) => this.flatListRef.scrollToEnd({ animated: false })}
              >

    然后从react native add导入键盘,然后将此代码添加到脚本中

    componentDidMount() {
        this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
    }
    }
    
     componentWillUnmount() {
        this.keyboardDidShowListener.remove();
        this.keyboardDidHideListener.remove();
      }
      
      _keyboardDidShow() {
        this.scrollView.scrollToEnd({ animated: false })
      }
    推荐文章