问题描述
const SlidingTabBar = (props) => {
const [active,setActive] = useState(0)
const [xTabOne,setXTabOne] = useState(0)
const [xTabTwo,setXTabTwo] = useState(0)
const [transX,setTransX] = useState(new Animated.Value(0))
const handleSlide = (type) => {
Animated.spring(transX,{
tovalue: type,duration: 100
}).start()
}
return (
<View style={styles.screen}>
<View style={styles.tabContainer}>
<Animated.View style={styles.active,{transform: [{ translateX: transX}]}} />
<TouchableOpacity onLayout={(e) => setXTabOne(e.nativeEvent.layout.x)} onPress={() => setActive(0),handleSlide(xTabOne)}><Text>tab one</Text></TouchableOpacity>
<TouchableOpacity onLayout={(e) => setXTabTwo(e.nativeEvent.layout.x)} onPress={() => setActive(1),handleSlide(xTabTwo)}><Text>tab 2</Text></TouchableOpacity>
</View>
</View>
);
}
const styles = StyleSheet.create({
screen: {
flex: 1,justifyContent: 'center',alignItems: 'center'
},tabContainer: {
flexDirection: 'row',borderWidth: 1,borderColor: 'blue',width: 300,justifyContent: 'space-around',position: 'relative',},active: {
position: 'absolute',backgroundColor: 'lightblue',width: '50%',height: '100%',left: 0,top: 0
}
})
但是当我在View组件上实现转换时,我的叠加层会消失并像这样破坏:
有什么建议吗?
解决方法
这很简单,我也在这方面挣扎,但我解决了
注意:代码用于功能组件
只需将 View 作为按钮容器,然后在它内部使用这样的按钮
<View style={styles.tabGroup}>
<TouchableOpacity
activeOpacity={0.6}
underlayColor="#0000ff"
onPress={()=> handleTab("tab1")}
style={[styles.tabButton,tab.tab1 && styles.tabButtonActive]}
>
<Text style={[styles.tabButtonTitle,tab.tab1 && styles.tabButtonTitleActive]}>Tab btn1</Text>
</TouchableOpacity>
<TouchableOpacity
activeOpacity={0.6}
underlayColor="#0000ff"
onPress={()=> handleTab("tab2")}
tyle={[styles.tabButton,tab.tab2 && styles.tabButtonActive]}
>
<Text style={[styles.tabButtonTitle,tab.tab2 && styles.tabButtonTitleActive]}>Tab btn2</Text>
</TouchableOpacity>
</View>
为按钮和按钮组添加一些样式
tabGroup:{
flexDirection: 'row',justifyContent: 'center',backgroundColor: 'rgba(11,93,30,0.11)',borderRadius: 46,marginHorizontal: 20,justifyContent: 'space-between'
},tabButton:{
backgroundColor: 'transparent',paddingHorizontal: 20,paddingVertical: 12,alignItems: 'center',},tabButtonActive:{
backgroundColor: '#0B5D1E',tabButtonTitle:{
fontSize: 16,fontWeight: 'normal',textAlign: 'center',color: '#000'
},tabButtonTitleActive:{
fontSize: 16,color: '#fff'
}
然后在上面定义函数和状态
const [tab,setTab] = useState({
tab1: false,tab2: true
});
const handleTab = (swap) =>{
if(swap==="tab1"){
setTab({
tab1: true,tab2: false
})
}
else{
setTab({
tab1: false,tab2: true
})
}
}