ReactNative 中的tabview点击tab无法切换view,
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { View, StyleSheet, Dimensions, Text } from 'react-native';
import { TabView, SceneMap, TabBar } from 'react-native-tab-view';
type Route = {
key: string;
title: string;
};
type State = {
index: number;
routes: Route[];
};
const initialTabState: State = {
index: 0,
routes: [
{ key: 'tab1', title: 'Tab 1' },
{ key: 'tab2', title: 'Tab 2' },
{ key: 'tab3', title: 'Tab 3' },
{ key: 'tab4', title: 'Tab 4' },
{ key: 'tab5', title: 'Tab 5' },
{ key: 'tab6', title: 'Tab 6' },
{ key: 'tab7', title: 'Tab 7' },
{ key: 'tab8', title: 'Tab 8' },
],
};
const FirstRoute = () => (
<View style={[styles.scene, { backgroundColor: '#ff4081' }]} />
);
const SecondRoute = () => (
<View style={[styles.scene, { backgroundColor: '#673ab7' }]} />
);
const ThirdRoute = () => (
<View style={[styles.scene, { backgroundColor: '#4caf50' }]} />
);
const FourthRoute = () => (
<View style={[styles.scene, { backgroundColor: '#2196f3' }]} />
);
const FifthRoute = () => (
<View style={[styles.scene, { backgroundColor: '#ffeb3b' }]} />
);
const SixthRoute = () => (
<View style={[styles.scene, { backgroundColor: '#9c27b0' }]} />
);
const SeventhRoute = () => (
<View style={[styles.scene, { backgroundColor: '#ffc107' }]} />
);
const EighthRoute = () => (
<View style={[styles.scene, { backgroundColor: '#607d8b' }]} />
);
const TabScreen: React.FC = () => {
const [tabState, setTabState] = useState<State>(initialTabState);
const renderScene = SceneMap({
'1': FirstRoute,
'2': SecondRoute,
'3': ThirdRoute,
'4': FourthRoute,
'5': FifthRoute,
'6': SixthRoute,
'7': SeventhRoute,
'8': EighthRoute,
});
const renderTabBar = (props: any) => (
<TabBar
{...props}
scrollEnabled
tabStyle={styles.tabStyle}
indicatorStyle={styles.indicatorStyle}
style={styles.tabBarStyle}
labelStyle={styles.labelStyle}
onTabPress={({ route }) => {
console.log(route)
const index = initialTabState.routes.findIndex(item => item.key == route.key);
handleIndexChange(index);
}}
/>
);
const handleIndexChange = (index: number) => {
setTabState({ ...tabState, index });
};
useEffect(() => {
console.log(tabState.index);
}, [tabState])
return (
<View style={{ flex: 1}}>
<TabView
navigationState={tabState}
renderScene={renderScene}
onIndexChange={handleIndexChange}
initialLayout={{ width: Dimensions.get('window').width }}
renderTabBar={renderTabBar}
/>
</View>
);
};
const styles = StyleSheet.create({
scene: {
flex: 1,
},
tabStyle: {
width: 'auto',
},
indicatorStyle: {
backgroundColor: '#000',
},
tabBarStyle: {
backgroundColor: '#fff',
},
labelStyle: {
color: '#000',
},
});
export default TabScreen;
"react": "18.2.0",
"react-native": "0.72.6",
"react-native-tab-view": "^3.5.1",
去除自定义tab改成原生的也不行
SceneMap
里面的key
需要initialTabState
里面routes
每一项的key
对应,然后你👀掉onTabPress 就可以了