[React Native] ScrollViewコンポーネントの使い方

スポンサーリンク

概要

React Nativeでスクロールが必要な場合、ViewコンポーネントではなくScrollViewコンポーネントを使用する。

  • スタイルのalignItemsやjustifyContentを指定するとエラーになるので注意。
  • keyboardDismissMode="on-drag"とすると、スクロール時にキーボードを閉じることができる。

サンプル

import { StyleSheet, Text, View, ScrollView } from "react-native";

export default function App() {
  return (
    <ScrollView style={styles.container}>
      〜省略〜
    </ScrollView>
  );
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#202328",
  },
});

一番下までスクロールさせる

useRefを使って以下のようにする。

const scrollView = useRef(null);
〜省略〜
<ScrollView ref={scrollView}>
〜省略〜
</ScrollView>
<Button title="一番下へ" onPress={() => scrollView.current.scrollToEnd()} />

おすすめ書籍

コメント