LoginSignup
13
8

More than 3 years have passed since last update.

React Native - ScrollViewで内容を追加しても常に最下部を表示する方法

Last updated at Posted at 2016-01-04

ScrollViewの内容を追加していくと
後に追加したものが隠れて見えなくなってしまいます。

デフォルトで勝手にスクロールするよってStack Overflowにあったりもしましたが
自分はうまくいかなかったのでソースで書いて頑張りました。

手順

①ScrollViewの高さを取得
②ScrollViewの中身の高さを取得
③上の2つの差を出してscrollToを実行

サンプルソース

main.js
・・・
  handleContentSizeChange: function(ctwidth, ctheight) {
    var height = this.state.scrollAreaHeight;
    if (height == 0) {
      return;
    }
    if (height < ctheight) {
      this.refs.scrollView.scrollTo(ctheight-height);
    }
  },
・・・
  render: function() {
    return (
・・・
        <ScrollView style={styles.scrollArea}
                    onLayout={(event) => {
                      var {x, y, width, height} = event.nativeEvent.layout;
                      this.setState({scrollAreaHeight: height});
                    }}
                    onContentSizeChange={this.handleContentSizeChange}
                    ref="scrollView">

・・・

こんな感じです。

onLayoutでコンポーネントがセットされた時の高さが取得できるので
onContentSizeChangeで中身のサイズが変わった時に
scrollToしてあげます。

13
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
8