LoginSignup
1
2

More than 1 year has passed since last update.

React Nativeでページ内遷移を実現する

Posted at

はじめに

React Nativeの開発をしているときに、ページ内遷移の実装を調べていたらReactのページ内リンクの記事ばかり上位に出てきたのでReact Nativeでの実装方法を記載します。

バージョン

"dependencies": {
    "react": "16.13.1",
    "react-native": "0.63.4",
}

実装方法

関数コンポーネントで定義しています。TypeScriptで書いてます。

import React, { useRef } from 'react';
import { View, ScrollView, Dimensions } from 'react-native';

const Index = () => {
  const scrollViewRef = useRef<ScrollView>(null);
  const [listPosition, setListPosition] = useState({} as Record<string, number>) // 要素のy座標
  // ページ内遷移
  const goToSection = (category: string) => {
    // スクロール後の位置の補正値
    const CORRECTION = 110
    // 指定のカテゴリのy座標を取得
    let height = listPosition[category] ?? 0
    height += CORRECTION
    if (scrollViewRef.current) {
      scrollViewRef.current.scrollTo({ x: 0, y: height, animated: true })
    }
  }
  return (
    <ScrollView ref={scrollViewRef}>
      {/* ページ内遷移ボタン */}
      <View>
        <TouchableWithoutFeedback onPress={() => goToSection('hoge')}>
          <Text>hoge</Text>
        </TouchableWithoutFeedback>
        <TouchableWithoutFeedback onPress={() => goToSection('fuga')}>
          <Text>fuga</Text>
        </TouchableWithoutFeedback>
        <TouchableWithoutFeedback onPress={() => goToSection('buzz')}>
          <Text>buzz</Text>
        </TouchableWithoutFeedback>
      </View>
      {/* コンテンツ */}
      <View
        key="hoge"
        onLayout={(e: any) => setMovieListHeight(e, "hoge")}>
      </View>
      <View
        key="fuga"
        onLayout={(e: any) => setMovieListHeight(e, "fuga")}>
      </View>
      <View
        key="buzz"
        onLayout={(e: any) => setMovieListHeight(e, "buzz")}>
      </View>
    </ScrollView>
  )
};

他にも実装方法がありましたらコメントください!:relaxed:

1
2
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
1
2