react-native-scrollable-tab-view自定義TabBar樣式

導入插件:

 npm install react-native-scrollable-tab-view --save

頁面引用:

import ScrollableTabView, {ScrollableTabBar, DefaultTabBar} from 'react-native-scrollable-tab-view';

先引用系統提供了兩種默認樣式:

DefaultTabBar:Tab會平分在水平方向的空間。
ScrollableTabBar:Tab可以超過屏幕範圍,滾動可以顯示。

效果:
在這裏插入圖片描述

<ScrollableTabView
    renderTabBar={() => <DefaultTabBar/>}>
           {
               label2.map((item, index) => {
                   return (
                       <View tabLabel={item} key={index} style={{flex:1,backgroundColor:'#fff',alignItems:'center',justifyContent:'center'}}>
                           <Text>{item}</Text>
                           <Text>{'DefaultTabBar'}</Text>
                       </View>
                   )
               })
           }
</ScrollableTabView>

在這裏插入圖片描述

<ScrollableTabView
     renderTabBar={() => <ScrollableTabBar/>}>
         {
             label1.map((item, index) => {
                 return (
                     <View tabLabel={item} key={index} style={{flex:1,backgroundColor:'#fff',alignItems:'center',justifyContent:'center'}}>
                         <Text>{item}</Text>
                         <Text>{'ScrollableTabBar'}</Text>
                     </View>
                 )
             })
         }
</ScrollableTabView>

自定義TabBar樣式:
在這裏插入圖片描述
//引入自定義tabbar樣式

  import SegmentTabBar from '../../components/segmentTabBar';

   <ScrollableTabView
          renderTabBar={() => <SegmentTabBar />}
          tabBarBackgroundColor='#3671ff'
          tabBarActiveTextColor='#fff'
           tabBarInactiveTextColor='#fff'>
           {
               label2.map((item, index) => {
                   return (
                       <View tabLabel={item} key={index} style={{flex:1,backgroundColor:'#fff',alignItems:'center',justifyContent:'center'}}>
                           <Text>{item}</Text>
                           <Text>{'自定義TabBar'}</Text>
                       </View>
                   )
               })
           }
        </ScrollableTabView>

segmentTabBar.js

/**
 * 創建: jiaojiao on 2018/10/29.
 * 功能:SegmentTabBar
 */
import React, {Component} from 'react'
import {
    View,
    Text,
    StyleSheet,
    TouchableOpacity,
    Dimensions,
} from 'react-native';
const PhoneWidth = Dimensions.get('window').width;
const Button = (props) => {
    return (
        <TouchableOpacity {...props} activeOpacity={0.95}>
            {props.children}
        </TouchableOpacity>
    )
};
export default class SegmentTabBar extends Component {

    constructor(props) {
        super(props);
        this.state = {
        };
    }
    renderTab(name, page, isTabActive, onPressHandler) {
        const textColor = isTabActive ? '#0086E5' : '#fff';
        const backgroundColor = isTabActive ? '#fff' : '#9bb8ff';
        console.log(textColor)
        return <Button
            style={{flex: 1, height: 25, backgroundColor}}
            key={name}
            accessible={true}
            accessibilityLabel={name}
            accessibilityTraits='button'
            onPress={() => onPressHandler(page)}
        >
            <View style={[styles.tab]}>
                <Text style={[{color: textColor, },]}>
                    {name}
                </Text>
            </View>
        </Button>;
    }

    render() {
        return (
            <View style={styles.tabBarBox}>
                <View style={ {flexDirection: 'row',width:150}}>
                    {this.props.tabs.map((name, page) => {
                        const isTabActive = this.props.activeTab === page;
                        const renderTab = this.props.renderTab || this.renderTab;
                        return renderTab(name, page, isTabActive, this.props.goToPage);
                    })}
                </View>
            </View>
        );
    }

}
const styles = StyleSheet.create({
    tabBarBox: {
        height: 50,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#3671ff',
    },
    iconBox: {
        margin: 15
    },
    tab: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    tabs: {
        borderRadius: 2,
        borderColor: '#0086E5',
        borderWidth: 1,
        width: PhoneWidth / 3,
        flexDirection: 'row',
        alignItems: 'center',
        alignContent: 'center',
        justifyContent: 'space-around',
    },
});

主頁全部代碼:

'use strict';
 import React, {PureComponent} from 'react';
 import {
     View,
     Text,
     StyleSheet,
 } from 'react-native';
 
import Header from '../../components/header'; //頭部導航
import ScrollableTabView, {ScrollableTabBar, DefaultTabBar} from 'react-native-scrollable-tab-view';
import SegmentTabBar from '../../components/segmentTabBar';

 export default class SrollableView extends PureComponent {
     static propTypes = {};
 constructor(props) {
     super(props);
     this.state = {
         label1: ['Tab1', 'Tab2','Tab3','Tab4','Tab5','Tab6','Tab7','Tab8'],
         label2: ['Tab1', 'Tab2'],
         tabShow: false,
     };
 }

 componentDidMount() {
     setTimeout(() => {
         this.setState({
             tabShow: true
         });
     }, 0)
 }

 // 滑動tab
 renderScrollableTab2() {
     let label1 = this.state.label1;
     if (this.state.tabShow) {
         return (
             <ScrollableTabView
                 renderTabBar={() => <ScrollableTabBar/>}>
                 {
                     label1.map((item, index) => {
                         return (
                             <View tabLabel={item} key={index} style={{flex:1,backgroundColor:'#fff',alignItems:'center',justifyContent:'center'}}>
                                 <Text>{item}</Text>
                                 <Text>{'ScrollableTabBar'}</Text>
                             </View>
                         )
                     })
                 }
             </ScrollableTabView>

         )
     }

 }
 // 滑動tab
 renderScrollableTab1() {
     let label1 = this.state.label1;
     if (this.state.tabShow) {
         return (
             <ScrollableTabView
                 renderTabBar={() => <DefaultTabBar/>}>
                 {
                     label1.map((item, index) => {
                         return (
                             <View tabLabel={item} key={index} style={{flex:1,backgroundColor:'#fff',alignItems:'center',justifyContent:'center'}}>
                                 <Text>{item}</Text>
                                 <Text>{'DefaultTabBar'}</Text>
                             </View>
                         )
                     })
                 }
             </ScrollableTabView>

         )
     }

 }
 // 滑動tab
 renderScrollableTab3() {
     let label2 = this.state.label2;
     if (this.state.tabShow) {
         return (
             <ScrollableTabView
                 renderTabBar={() => <SegmentTabBar />}
                 tabBarBackgroundColor='#3671ff'
                 tabBarActiveTextColor='#fff'
                 tabBarInactiveTextColor='#fff'>
                 {
                     label2.map((item, index) => {
                         return (
                             <View tabLabel={item} key={index} style={{flex:1,backgroundColor:'#fff',alignItems:'center',justifyContent:'center'}}>
                                 <Text>{item}</Text>
                                 <Text>{'自定義TabBar'}</Text>
                             </View>
                         )
                     })
                 }
             </ScrollableTabView>
         )
     }

 }
 render() {
     return (
         <View style={styles.container}>
             <Header title={"ScrollableTab"} style={[styles.header]} />
             {/*{this.renderScrollableTab1()}*/}
             {/*{this.renderScrollableTab2()}*/}
             {this.renderScrollableTab3()}

         </View>
     );
 }

 }

 const styles = StyleSheet.create({
     container: {
         flex: 1,
     },
 });

ScrollableTabView具體屬性這篇寫的挺詳細的,下面。。嘿嘿,我直接挪過來啦!!方便以後使用

作者:code_xzh
來源:CSDN
原文:https://blog.csdn.net/xiangzhihong8/article/details/72730951
屬性及方法介紹

1, renderTabBar(Function:ReactComponent)

TabBar的樣式,系統提供了兩種默認的,分別是DefaultTabBar和ScrollableTabBar。當然,我們也可以自定義一個,我們會在下篇文章重點講解如何去自定義TabBar樣式。
注意:每個被包含的子視圖需要使用tabLabel屬性,表示對應Tab顯示的文字。
DefaultTabBar:Tab會平分在水平方向的空間。
ScrollableTabBar:Tab可以超過屏幕範圍,滾動可以顯示。

render() {
  return (
    <ScrollableTabView
      renderTabBar={() => <DefaultTabBar/>}>
      <Text tabLabel='Tab1'/>
      <Text tabLabel='Tab2'/>
      <Text tabLabel='Tab3'/>
      <Text tabLabel='Tab4'/>
      <Text tabLabel='Tab5'/>
      <Text tabLabel='Tab6'/>
    </ScrollableTabView>
  );
}

2,tabBarPosition(String,默認值’top’)
top:位於屏幕頂部
bottom:位於屏幕底部
overlayTop:位於屏幕頂部,懸浮在內容視圖之上(看顏色區分:視圖有顏色,Tab欄沒有顏色)
overlayBottom:位於屏幕底部,懸浮在內容視圖之上(看顏色區分:視圖有顏色,Tab欄沒有顏色)

render() {
  return (
    <ScrollableTabView
      tabBarPosition='top'
      renderTabBar={() => <DefaultTabBar/>}>
      ...
    </ScrollableTabView>
  );
}

3, onChangeTab(Function)
Tab切換之後會觸發此方法,包含一個參數(Object類型),這個對象有兩個參數:
i:被選中的Tab的下標(從0開始)
ref:被選中的Tab對象(基本用不到)

render() {
  return (
    <ScrollableTabView
      renderTabBar={() => <DefaultTabBar/>}
      onChangeTab={(obj) => {
          console.log('index:' + obj.i);
        }
      }>
      ...
    </ScrollableTabView>
  );
}

4,onScroll(Function)
視圖正在滑動的時候觸發此方法,包含一個Float類型的數字,範圍是[0, tab的數量-1]

render() {
  return (
    <ScrollableTabView
      renderTabBar={() => <DefaultTabBar/>}
      onScroll={(postion) => {  
          // float類型 [0, tab數量-1]  
          console.log('scroll position:' + postion);
        }
      }>
      ...
    </ScrollableTabView>
  );
}

5, locked(Bool,默認爲false)
表示手指是否能拖動視圖,默認爲false(表示可以拖動)。設爲true的話,我們只能“點擊”Tab來切換視圖。

render() {
  return (
    <ScrollableTabView
      locked={false}
      renderTabBar={() => <DefaultTabBar/>}>
      ...
    </ScrollableTabView>
  );
}

6, initialPage(Integer)
初始化時被選中的Tab下標,默認是0(即第一頁)。

render() {
  return (
    <ScrollableTabView
      initialPage={1}
      renderTabBar={() => <DefaultTabBar/>}>
      ...
    </ScrollableTabView>
  );
}

7,page(Integer)
設置選中指定的Tab。

8,children(ReactComponents)
表示所有子視圖的數組,比如下面的代碼,children則是一個長度爲6的數組,元素類型爲Text。

render() {
  return (
    <ScrollableTabView
      renderTabBar={() => <DefaultTabBar/>}>
      <Text tabLabel='Tab1'/>
      <Text tabLabel='Tab2'/>
      <Text tabLabel='Tab3'/>
      <Text tabLabel='Tab4'/>
      <Text tabLabel='Tab5'/>
      <Text tabLabel='Tab6'/>
    </ScrollableTabView>
  );
}

9,tabBarUnderlineStyle(style)
設置DefaultTabBar和ScrollableTabBarTab選中時下方橫線的顏 色。
10.,tabBarBackgroundColor(String)
設置整個Tab這一欄的背景顏色
11,tabBarActiveTextColor(String)
設置選中Tab的文字顏色。
12,tabBarInactiveTextColor(String)
設置未選中Tab的文字顏色。
13,contentProps(Object)
這裏要稍微說下react-native-scrollable-tab-view的實現,其實在Android平臺底層用的是ViewPagerAndroid,iOS平臺用的是ScrollView。這個屬性的意義是:比如我們設置了某個屬性,最後這個屬性會被應用在ScrollView/ViewPagerAndroid,這樣會覆蓋庫裏面默認的,通常官方不建議我們去使用。
14,scrollWithoutAnimation(Bool,默認爲false)
設置“點擊”Tab時,視圖切換是否有動畫,默認爲false(即:有動畫效果)。

render() {
  return (
    <ScrollableTabView
      scrollWithoutAnimation={true}
      renderTabBar={() => <DefaultTabBar/>}>
      ...
    </ScrollableTabView>
  );
}

頂部導航示例

頂部導航的代碼是比較簡單的。例如,我們實現上圖的新聞Tab導航的效果。
這裏寫圖片描述

相關代碼:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

 import React, { Component } from 'react';
 import ScrollableTabView, {DefaultTabBar,ScrollableTabBar} from 'react-native-scrollable-tab-view';
 import {
   AppRegistry,
   StyleSheet,
   Text,
   Image,
   View
 } from 'react-native';

var Dimensions = require('Dimensions');
var ScreenWidth = Dimensions.get('window').width;

class TabTopView extends Component {
    render() {
        return (
            <ScrollableTabView
                style={styles.container}
                renderTabBar={() => <DefaultTabBar />}
                tabBarUnderlineStyle={styles.lineStyle}
                tabBarActiveTextColor='#FF0000'>

                <Text style={styles.textStyle} tabLabel='娛樂'>娛樂</Text>
                <Text style={styles.textStyle} tabLabel='科技'>科技</Text>
                <Text style={styles.textStyle} tabLabel='軍事'>軍事</Text>
                <Text style={styles.textStyle} tabLabel='體育'>體育</Text>
            </ScrollableTabView>
        );
    }
    }


 const styles = StyleSheet.create({
     container: {
         flex: 1,
         marginTop: 20
     },
     lineStyle: {
         width:ScreenWidth/4,
         height: 2,
         backgroundColor: '#FF0000',
     },
     textStyle: {
         flex: 1,
         fontSize:20,
         marginTop:20,
         textAlign:'center',
     },

 });

export default TabTopView;

然後在index.ios.js或index.android.js中導入組件。

export default class RNDemo extends Component {
    render() {
        return (
            <TabBottomView/>
        );
    }
}

底部Tab切換示例

這裏寫圖片描述

需要注意的是項目中用到了Navigator這個組件,在最新的版本中,系統標識Navigator已經過時被拋棄,所以我們需要使用命令先按照相關的庫:

npm install --save react-native-deprecated-custom-components

在這裏插入圖片描述

然後在使用的界面中導入Navigator。

import {
    Navigator,
} from 'react-native-deprecated-custom-components';

好了其他的不再說明,直接上代碼:
TabBottomView.js

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow react-native-scrollable-tab-view 底部切換
 */

import React, {Component} from 'react';
import ScrollableTabView from 'react-native-scrollable-tab-view';
import TabBottom from '../component/TabBottom';
import HomeScreen from './HomeScreen';
import MineScreen from './MineScreen';

const tabTitles = ['首頁', '我的'];
//默認圖標
const tabIcon = [
    require('../images/tabbar_homepage.png'),
    require('../images/tabbar_mine.png'),
];
//選中圖標
const tabSelectedIcon = [
    require('../images/tabbar_homepage_selected.png'),
    require('../images/tabbar_mine_selected.png'),
];

export default class TabBottomView extends Component {

    onChangeTabs = ({i}) => 'light-content';

    render() {
        return (
            <ScrollableTabView
                renderTabBar={() =>
                    <TabBottom
                        tabNames={tabTitles}
                        tabIconNames={tabIcon}
                        selectedTabIconNames={tabSelectedIcon}/>}
                tabBarPosition='bottom'
                onChangeTab={this.onChangeTabs}>

                <HomeScreen  navigator={this.props.navigator}/>
                <MineScreen  navigator={this.props.navigator}/>

            </ScrollableTabView>
        );
    }
}

其中,TabBottom自定義組件代碼
TabBottom.js

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow TextInput自動提示輸入
 */

import React, {Component} from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    TouchableOpacity,
    Image,
    View
}
from
'react-native';

export default class TabBottom extends Component {

    static propType = {
        goToPage    : React.PropTypes.func,
        activeTab   : React.PropTypes.number,
        tabs        : React.PropTypes.array,

        tabNames    : React.PropTypes.array,
        tabIconNames: React.PropTypes.array,
        selectedTabIconNames: React.PropTypes.array
    };

    componentDidMount() {
        this.props.scrollValue.addListener(this.setAnimationValue);
    }

    setAnimationValue({value}) {
        console.log(value);
    }

    render() {
        return (
            <View style={styles.tabs}>
                {this.props.tabs.map((tab, i) => {
                    let color = this.props.activeTab === i ? 'green' : 'gray';
                    let icon = this.props.activeTab == i ? this.props.selectedTabIconNames[i] : this.props.tabIconNames[i];
                    return (
                        <TouchableOpacity
                            key={i}
                            activeOpacity={0.8}
                            style={styles.tab}
                            onPress={()=>this.props.goToPage(i)}>
                            <View style={styles.tabItem}>
                                <Image
                                    style={styles.icon}
                                    source={icon}/>
                                <Text style={{color: color, fontSize: 12}}>
                                    {this.props.tabNames[i]}
                                </Text>
                            </View>
                        </TouchableOpacity>
                    )
                })}
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#ffffff',
        marginTop: 20
    },
    tabs: {
        flexDirection: 'row',
        height: 49,
        borderTopColor: '#d9d9d9',
        borderTopWidth:2
    },
    tab: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    tabItem: {
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'space-around'
    },
    icon: {
        width: 26,
        height: 26,
        marginBottom: 2
    }
});

最後在index.ios.js或index.android.js中導入組件。

export default class RNDemo extends Component {
    render() {
        return (
            <TabBottomView/>
        );
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章