5
4

More than 3 years have passed since last update.

react-navigation-tabsのタブのスタイルを変更する

Posted at

はじめに

初投稿です。読み難い点があるかもしれませんが、ご容赦ください。

やりたいこと

上部タブの幅をテキストの長さによって可変にしたい。また、タブの数が多い場合はスクロールしたい。(メ○カリのようなUIが目標)

開発環境

react-navigation:4.0.10
react-navigation-tabs:2.6.0

変更前

上部タブの幅が等間隔になっており、テキストが折り返されている。
Simulator Screen Shot - iPhone X - 2019-12-02 at 14.49.25.png

変更(追加)内容

tabBarOptionsの中で
・tabStyleのwidthを'auto'にする
・scrollEnabledをtrueにする

Tab.js
import React from 'react';
import { View } from 'react-native';
import { Text } from 'native-base';
import { createMaterialTopTabNavigator } from 'react-navigation-tabs';

class HomeScreen01 extends React.Component {
  render() {
    return (
      <View style = {{ flex:1, alignItems: 'center', justifyContent: 'center'}}>
        <Text>保存した検索条件</Text>
      </View>
    );
  }
}

class HomeScreen02 extends React.Component {
  render() {
    return (
      <View style = {{ flex:1, alignItems: 'center', justifyContent: 'center'}}>
      <Text>おすすめ</Text>
    </View>
    );
  }
}

class HomeScreen03 extends React.Component {
  render() {
    return (
      <View style = {{ flex:1, alignItems: 'center', justifyContent: 'center'}}>
        <Text>新着</Text>
      </View>
    );
  }
}

class HomeScreen04 extends React.Component {
  render() {
    return (
      <View style = {{ flex:1, alignItems: 'center', justifyContent: 'center'}}>
        <Text>レディース</Text>
      </View>
    );
  }
}

export default createMaterialTopTabNavigator(
  {
    Home01: {
      screen: HomeScreen01,
      navigationOptions: () => ({
        tabBarLabel: "保存した検索条件"
      }),
    },
    Home02: {
      screen: HomeScreen02,
      navigationOptions: () => ({
        tabBarLabel: "おすすめ",
      }),
    },
    Home03: {
      screen: HomeScreen03,
      navigationOptions: () => ({
        tabBarLabel: "新着",
      }),
    },
    Home04: {
      screen: HomeScreen04,
      navigationOptions: () => ({
        tabBarLabel: "レディース",
      }),
    },
  },
  {
    initialRouteName: 'Home02',
    tabBarOptions: {
      activeTintColor: '#e3463d',
      inactiveTintColor: '#c4c4c4',
      style: {
        backgroundColor: '#ffffff',
        paddingTop: 40,
      },
      indicatorStyle: {
        backgroundColor: '#e3463d',
        height: 3,
      },
      labelStyle: {
        fontSize: 15,
        fontWeight: 'bold',
      },
      scrollEnabled: true,
      tabStyle: {
        width: 'auto'
      }
    }
  },
)

変更後

上部タブの幅が変わりスクロールできるようになりました。
Simulator Screen Shot - iPhone X - 2019-12-02 at 14.48.26.png

参考記事

タブの組み込み方は下記の記事を参考にさせていただきました。
タブ(TabNavigator)をコンポーネント化してスクリーン内に組み込む

さいごに

ReactNativeの技術習得のアウトプットとして記事を書いてみました。

5
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
5
4