RN自定义CustomTabBar及点击事件
2018-06-11 本文已影响170人
OnceWhite
根据react-navigation 自定义TabBar
引入react-navigation 直接上代码
const Tab = TabNavigator(
...
{
tabBarComponent: CustomTabBar,//TabBarBottom, //默认组件
tabBarPosition: 'bottom',
swipeEnabled: false,
animationEnabled: false,
lazy: true,
tabBarOptions: {
style: { backgroundColor: 'transparent' },
},
}
);
自定义的CustomTabBar
import React, {Component} from 'react';
import {
View,
TouchableOpacity,
Text,
StyleSheet,
Image,
Dimensions,
ImageBackground
} from 'react-native';
......
const {width} = Dimensions.get('window');
class CustomTabBar extends Component {
render() {
let navigation = this.props.navigation;
let icons = [];
let titles = [
'首页',
'关注',
'直播',
'消息',
'我'
];
const { routes, index } = navigation.state;
const backgroundColor = (index == 0) ? 'transparent' : IConstants.Custom_TabBarBg;
return (
// 下面即可自定义
<View style={[styles.tabContainer,{backgroundColor}]}>
// 背景图片
<Image style={{width:width,height:48,position:'absolute',top:0,left:0,zIndex:0}}
source={require('../assets/images/tabBg.png')}
/>
{routes.map((route, idx) => {
const color = (index === idx) ? '#fff' : '#999';
const isActive = index === idx;
return (
<TouchableOpacity
activeOpacity={1}
onPress={() => {
if(index === idx && idx != 2){
Toast.show('再次点击选中Tab事件',{position: Toast.positions.CENTER});
DeviceEventEmitter.emit(IConstants.EventType.HOME_REFRESH,{});
}else if(idx == 2){
Toast.show('某一个tab点击事件', {position: Toast.positions.CENTER});
}
else{
//tab切换事件
navigation.navigate(route.routeName);
}
}}
style={[styles.tab]}
key={route.routeName}
>
{
idx === 2
?
<Image
style={{ width: 42, height: 27 }}
source={icons[idx]}/>
:
<View style={styles.tabView}>
<Text style={{ color,fontSize: isActive ? 15 : 14,fontWeight:isActive ? 'bold' :'normal' }}>{titles[idx]}</Text>
<View style={[styles.bottomLine,{backgroundColor:isActive ? '#fff' : 'transparent'}]}></View>
</View>
}
{
idx == 1 || idx == 3
?
<View style={styles.dotPoint}></View>
:null
}
</TouchableOpacity>
)
})}
</View>
);
}
}
const styles = StyleSheet.create({
......
})
export default CustomTabBar;
监听事件 DeviceEventEmitter (也可以用redux)
1.引入DeviceEventEmitterimport { .....,DeviceEventEmitter} from 'react-native'2.发事件
DeviceEventEmitter.emit(IConstants.EventType.HOME_REFRESH,{}); //发监听3.在需要响应的页面接收监听
//收到监听 this.homeListener = DeviceEventEmitter.addListener(IConstants.EventType.HOME_REFRESH>,(e)=>{ ..... //处理事件 }); //不用了记得移除 componentWillUnmount(){ this.homeListener.remove(); };