react-native动态切换tab组件的⽅法
在APP中免不了要使⽤tab组件,有的是tab切换,也有的是tab分类切换.
这些组件分成下⾯两种.
第⼀种⾮常简单,同时⼤多数第三⽅组件都能达到效果.这⾥重点讲述第⼆种,我们要让第⼆种组件不仅能左右滑动,同时还能够在点击的时候⾃动滑动,将点击的位置滑动到正中间.
准备
我们先来分析⼀波.⼀个滑动组件在APP上是⼀种什么状态.
这⾥可以看出,tab组件需要考虑到长度超过APP的屏幕,并且在超过之后能够滑动.
同时计算出当前位置需要滑动多少距离才能够将位置居中.
需要滑动的位置=点击位置的左边距-APP屏幕/2+点击位置的宽度/2
这个公式也就是我们⾃动滑动的核⼼了.
开发
使⽤ScrollView组件承载tab项,这样就可以⾮常简单的达到滑动的效果.同时添
加horizontal、directionalLockEnabled、showsHorizontalScrollIndicator、snapToAlignment⼏个属性.
<ScrollView ref={e => this.scroll = e}
horizontal directionalLockEnabled
showsHorizontalScrollIndicator={false}
snapToAlignment="center">
{this.props.data.map((item, index) =>
{/*具体项*/}
)
}
</ScrollView>
使⽤TouchableOpacity包裹内容项,同时调⽤setLaout⽅法将每个项的宽⾼等属性记录下来,为我们后⾯计算当前位置做准备.
<TouchableOpacity onPress={() => this.setIndex(index)}
react to后面接什么onLayout={e => this.setLaout(e.nativeEvent.layout, index)}
key={item.id}
style={tabBarStyle.itemBtn}>
<Text style={[tabBarStyle.item, this.state.index === index ? tabBarStyle.active : null]} > {item.name}</Text>  <View style={[tabBarStyle.line, this.state.index === index ? tabBarStyle.active2 : null]}>    </View>
</TouchableOpacity>
记录每个项渲染之后的位置,将这些值存在变量⾥,为后⾯计算做准备.
laout_list = []
setLaout(layout, index) {
//存单个项的位置
this.laout_list[index] = layout;
//计算所有项的总长度
this.scrollW += layout.width;
}
接下来就是点击⾃动变换位置的计算了.
setIndex(index, bl = true) {
//先改变点击项的颜⾊
this.setState({ index })
//兼容错误
if (!this.scroll) return;
//拿到当前项的位置数据
let layout = this.laout_list[index];
let rx = deviceWidth / 2;
//公式
let sx = layout.x - rx + layout.width / 2;
//如果还不需要移动,原地待着
if (sx < 0) sx = 0;
//移动位置
sx < this.scrollW - deviceWidth && this.scroll.scrollTo({ x: sx, animated: bl });
//结尾部分直接移动到底
sx >= this.scrollW - deviceWidth && this.scroll.scrollToEnd({ animated: bl });
//触发⼀些需要的外部事件
Change && Change(index);
}
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。