LoginSignup
7
4

More than 3 years have passed since last update.

【React Native】ScrollView

Posted at

概要

  • ページ内にいくつかのコンポーネントを表示したいが画面からはみ出してしまった場合などにScrollViewを用いる。

→ 理由はViewコンポーネントを使用した場合では、はみ出した要素をスクロールして確認する事が出来ないためである。

  • ScrollViewはラップしている全ての子要素を一度にレンダリングさせるため、パフォーマンスはあまり良くない。(FlatListはlazyロードするので一度に全てを表示する事はない)
  • ScrollView内でmap処理などをする事があればFlatListコンポーネントを使うべきである。
  • ScrollViewを用いれば縦スクロールだけでなく横スクロールの制御も可能になる。
  • contentContainerStyleでList内のスタイルを設定する事が出来る。

公式の見解

ScrollViewは、限られたサイズのものを表示するのに最適である。
ScrollView内ではスクリーン上に表示されていない要素含め全ての要素がレンダリングされてしまう。
画面内に収まりきらない多くのアイテムリストを表示させる場合、ScrollViewの代わりにFlatListを使用すべきである。

ScrollView使用時の親要素のスタイルはflexGrow: 1

scrollEnabledがtrueの場合のみ要素のスクロールが可能になる

→ defaultではスクロール可能になっているので要素が画面より大きい場合にスクロールONにする時などに有効

const [contentHeight, setContentHeight] = useState(0);
const handleContentSizeChange = (width, height) => {
  setContentHeight(height);
};
const {width, height} = Dimensions.get('window'); // hooksのuseWindowDimensions()を用いてもwidht, heightを取得する事が出来る
const scrollEnabled = contentHeight > height;

// rootはflexGrow: 1にしないと要素が表示されなくなる
<SafeAreaView style={styles.root}>
  <ScrollView
    contentContainerStyle={styles.scrollView}
    onContentSizeChange={handleContentSizeChange}
        scrollEnabled={scrollEnabled}
  >
    <Text style={styles.text}>
      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo,
      inventore, maiores? Accusantium iure nam odio officia. Aut autem,
      consequuntur cum dignissimos dolorum excepturi fugiat hic minima
      molestias nesciunt provident ut?
    </Text>
  </ScrollView>
</SafeAreaView>

スクロールバーを表示させない

showsVerticalScrollIndicatorにfalseを渡す事でスクロールバーを非表示にする。

<ScrollView showsVerticalScrollIndicator={false}>
    <Text style={styles.text}>React Native</Text>
</ScrollView>

横スクロールの実装

ScrollViewコンポーネントにhorizonalを渡す事で横スクロールに対応する事が可能。

<ScrollView horizonal>
    <Text style={styles.text}>React Native</Text>
</ScrollView>
7
4
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
7
4