在APP中免不了要使用tab组件,有的是tab切换,也有的是tab分类切换.javascript
这些组件分红下面两种.java
第一种很是简单,同时大多数第三方组件都能达到效果.这里重点讲述第二种,咱们要让第二种组件不只能左右滑动,同时还可以在点击的时候自动滑动,将点击的位置滑动到正中间.react
咱们先来分析一波.一个滑动组件在APP上是一种什么状态.git
这里能够看出,tab组件须要考虑到长度超过APP的屏幕,而且在超过以后可以滑动.github
同时计算出当前位置须要滑动多少距离才可以将位置居中.须要滑动的位置=点击位置的左边距-APP屏幕/2+点击位置的宽度/2
react-native
这个公式也就是咱们自动滑动的核心了.this
使用ScrollView
组件承载tab项,这样就能够很是简单的达到滑动的效果.同时添加horizontal
、directionalLockEnabled
、showsHorizontalScrollIndicator
、snapToAlignment
几个属性.spa
<ScrollView ref={e => this.scroll = e} horizontal directionalLockEnabled showsHorizontalScrollIndicator={false} snapToAlignment="center"> {this.props.data.map((item, index) => {/*具体项*/} )} </ScrollView>
使用TouchableOpacity
包裹内容项,同时调用setLaout
方法将每一个项的宽高等属性记录下来,为咱们后面计算当前位置作准备.code
<TouchableOpacity onPress={() => this.setIndex(index)} 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>
记录每一个项渲染以后的位置,将这些值存在变量里,为后面计算作准备.blog
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 }); //触发一些须要的外部事件 this.props.onChange && this.props.onChange(index); }
最后上一张结果图: