当前位置: 移动技术网 > IT编程>开发语言>JavaScript > react-native动态切换tab组件的方法

react-native动态切换tab组件的方法

2019年06月05日  | 移动技术网IT编程  | 我要评论

在app中免不了要使用tab组件,有的是tab切换,也有的是tab分类切换.

这些组件分成下面两种.


第一种非常简单,同时大多数第三方组件都能达到效果.这里重点讲述第二种,我们要让第二种组件不仅能左右滑动,同时还能够在点击的时候自动滑动,将点击的位置滑动到正中间.

准备

我们先来分析一波.一个滑动组件在app上是一种什么状态.

这里可以看出,tab组件需要考虑到长度超过app的屏幕,并且在超过之后能够滑动.

同时计算出当前位置需要滑动多少距离才能够将位置居中.
需要滑动的位置=点击位置的左边距-app屏幕/2+点击位置的宽度/2

这个公式也就是我们自动滑动的核心了.

开发

使用scrollview组件承载tab项,这样就可以非常简单的达到滑动的效果.同时添加horizontaldirectionallockenabledshowshorizontalscrollindicatorsnaptoalignment几个属性.

<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)} 
 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 });
 //触发一些需要的外部事件
 this.props.onchange && this.props.onchange(index);
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网