使用
import ScrollableTabView from 'react-native-scrollable-tab-view';
import { CmvTabs, Nodata } from '@/components';
<ScrollableTabView
initialPage={initTabIndex}
onChangeTab={(data) => onChangeTab(data)}
renderTabBar={() => <CmvTabs />}
>
<View tabLabel="病例交流" style={styles.tabView}>
<FlatList .../>
</View>
<View tabLabel="热点文章" style={styles.tabView}>
<FlatList .../>
</View>
<View tabLabel="精品课程" style={styles.tabView}>
<FlatList .../>
</View>
<View tabLabel="期刊文献" style={styles.tabView}>
<FlatList .../>
</View>
</ScrollableTabView>
cmv-tabs.js
import React from 'react';
import { StyleSheet, View, Animated, TouchableOpacity } from 'react-native';
import { Text } from '@/components';
export function CmvTabs(props) {
const renderTab = (name, index, isTabActive, onPressHandler) => {
const activeTextColor = '#333333';
const inactiveTextColor = '#999999';
const textColor = isTabActive ? activeTextColor : inactiveTextColor;
const fontWeight = isTabActive ? 'bold' : 'normal';
const fontSize = isTabActive ? 16 : 14;
return (
<TouchableOpacity
key={index}
onPress={() => {
onPressHandler(index);
}}
>
<View style={{ backgroundColor: '#fff' }}>
<Text
text={name}
style={{
fontWeight: fontWeight,
color: textColor,
fontSize: fontSize
}}
></Text>
</View>
</TouchableOpacity>
);
};
const containerWidth = props.containerWidth;
const numberOfTabs = props.tabs.length;
const translateX = props.scrollValue.interpolate({
inputRange: [0, 1],
outputRange: [0, containerWidth / numberOfTabs]
});
const leftDistance = (underlineWidth) =>
(containerWidth / numberOfTabs - underlineWidth) / 2;
return (
<View style={styles.tabs}>
{props.tabs.map((name, index) => {
const isTabActive = props.activeTab === index;
return renderTab(name, index, isTabActive, props.goToPage);
})}
<Animated.View
style={[
{
transform: [{ translateX }]
},
styles.underlineStyle,
{
width: 20,
left: leftDistance(20)
}
]}
/>
</View>
);
}
const styles = StyleSheet.create({
tabs: {
// tab整个的高度
height: 50,
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
borderTopWidth: 0,
borderLeftWidth: 0,
borderRightWidth: 0,
// 下边框
borderBottomWidth: 0,
borderColor: '#ccc',
// 背景色
backgroundColor: '#fff'
},
underlineStyle: {
position: 'absolute',
height: 4,
backgroundColor: '#0077F6',
borderRadius: 2,
bottom: 5
}
});
效果
问题
在 Android 上报错 requireNativeComponent: "RNCViewPager" was not found in the UIManager
解决:
// 直接下载就行,RN会autolink,如果你版本低就要手动link
yarn add @react-native-community/viewpager
// 重新打包
yarn android 或 react-native run android
亲测有效
https://www.npmjs.com/package/@react-native-community/viewpager
这是包的地址,虽然提示此包已经不维护了,推荐另一个包,但是我用另一个包,切换的时候页面空白,所以还是用这个包解决了问题。
tab切换别的方法
使用 react navigation,就和 tabbar 一样,只不过在上面。