PUROGU LADESU

ポエムがメインのブログです。

【ReactNative】タブでビュー切り替え

f:id:memorude:20200811165900g:plain

やり方はとりあえず2通りあります。 他にもButtonGropuとか使って、自前でScrollViewをスライドさせたらできそうです。

react-native-tab-viewを使う

github.com

Viewを用意して、切り替えます。
routesにはタブを定義します。
renderSceneに表示させるViewを定義します。
scrollEnabledはタブの横スクロールを可能にします。タブが増えたとき用。

import { TabView, SceneMap, ScrollPager, TabBar } from 'react-native-tab-view';

const TopTabView = () => {
  const [index, setIndex] = React.useState(0);
  const [routes] = React.useState([
    { key: 'first', title: 'Notification' },
    { key: 'second', title: 'Information' },
    { key: 'third', title: 'Todo' },
  ]);

  const initialLayout = { width: Dimensions.get('window').width };

  const renderScene = SceneMap({
    first: NotificationScreen,
    second: InformationScreen,
    third: TodoScreen,
  });

  // returnの省略形
  const renderTabBar = (props) => (
    <TabBar
      {...props}
      indicatorStyle={{ backgroundColor: '#e91e63' }}
      style={{ backgroundColor: 'white' }}
      labelStyle={{ color: 'black' }}
      scrollEnabled={true}
      // tabStyle={{ width: 140 }}
      // tabStyle={{ width: 'auto' }}
    />
  );

  return (
    <TabView
      navigationState={{ index, routes }}
      renderScene={renderScene}
      onIndexChange={setIndex}
      initialLayout={initialLayout}
      renderPager={(props) => <ScrollPager {...props} />}
      renderTabBar={renderTabBar}
    />
  );
};

const NotificationScreen = () => {
  return (
    <View style={styles.container}>
      <Text>NotificationScreen</Text>
    </View>
  );
};

react-navigationのcreateMaterialTopTabNavigatorを使う

reactnavigation.org

試してませんが画面遷移したいときはこっちにするべきかも。 上記のreact-native-tab-viewをラップしてるらしいので、機能は同じだと思います。

import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs';

const NotificationTab = createMaterialTopTabNavigator();
const NotificationTabNavigator = () => {
  return (
    <NotificationTab.Navigator
      tabBarOptions={{
        scrollEnabled: true,
        indicatorStyle: { backgroundColor: '#e91e63' },
        // tabStyle: { width: 'auto' },
      }}
    >
      <NotificationTab.Screen
        name="Notification"
        component={NotificationScreen}
      />
      <NotificationTab.Screen name="Infomation" component={InformationScreen} />
      <NotificationTab.Screen name="Todo" component={TodoScreen} />
    </NotificationTab.Navigator>
  );
};