现象:最近开发RN项目,在使用ant-design的tabs标签的时候,发现标签是可以左右滑动切换,但是无法点击标签切换。
原因:不知
解决方案: renderTabBar时设置TabBar渲染组件 goToTab切换标签
- index.tsx
/** “tab” 页面 */
import React, { Component } from 'react'
import { View, Text } from 'react-native'
import { Tabs } from '@ant-design/react-native'
import TabBar from './tab-bar'
interface IState {
currentNav: number
}
export class HomeScreen extends Component<any, IState> {
readonly state: IState = {
currentNav: 0
}
render() {
const tabs = [
{ title: '进行中' },
{ title: '已结束' }
]
return (
<View style={{ flex: 1 }}>
<Tabs
tabs={tabs}
renderTabBar={(props) =>
<TabBar
goToTab={(index) => true}
{...props}
/>
}
onChange={(_tab, index) => {
this.setState({ currentNav: index })
}}
>
<View>
<Text>进行中数据</Text>
</View>
<View>
<Text>已结束数据</Text>
</View>
</Tabs>
</View>
)
}
}
- tab-bar.tsx
import React, { Component } from "react"
import { View, ViewStyle, TextStyle, StyleSheet, Text, TouchableOpacity } from "react-native"
interface IProps {
activeTab: String | number,
goToTab: any,
tabs: any[]
}
export default class TabBar extends Component<IProps, any> {
render() {
const { tabs, activeTab, goToTab } = this.props
return (
<View style={styles.tabBar}>
{tabs.map((item, index) => {
return (
<View style={{ flex: 1, alignItems: 'center' }} key={index}>
<TouchableOpacity
key={index}
onPress={() => goToTab(index)}
>
<Text style={[styles.tabBarItemText, activeTab === index ? styles.tabBarActiveText : null]}>{item.title}</Text>
</TouchableOpacity>
</View>
)
})}
</View>
)
}
}
interface Styles {
tabBar: ViewStyle,
tabBarActiveText: TextStyle,
tabBarItemText: TextStyle,
}
const styles = StyleSheet.create<Styles>({
tabBar: {
height: 50,
flexDirection: 'row'
},
tabBarActiveText: {
height: 50,
borderBottomWidth: 3,
borderBottomColor: '#3356D9',
color: '#3356D9',
fontWeight: 'bold'
},
tabBarItemText: {
fontWeight: '400',
fontSize: 20,
width: 70,
height: 50,
lineHeight: 50,
color: '#333',
textAlign: 'center'
}
})
demo所用的安装包 "@ant-design/react-native": "3.1.9"