本文基于React Native 0.52react
Demo上传到Git了,有须要能够看看,写了新内容会上传的。Git地址 https://github.com/gingerJY/React-Native-Demogit
以下图,有一个滑动的tab切换,就是用react-native-scrollable-tab-view来实现的。github
一、经过npm将插件加入项目npm
npm install react-native-scrollable-tab-view --save
二、在home.js引入插件react-native
import ScrollableTabView, { ScrollableTabBar, DefaultTabBar } from 'react-native-scrollable-tab-view';
三、使用插件less
① 这里就写一下我这个效果的实现,其余内容能够看 https://github.com/skv-headless/react-native-scrollable-tab-view布局
② TabBar有DefaultTabBar
和ScrollableTabBar两种,这里使用ScrollableTabBar,下面是官方给出的例子(若是是在APP的首页会出现内容不显示的问题,三里面有解决办法)
this
<ScrollableTabView initialPage={0} renderTabBar={() => <ScrollableTabBar />} > <Text tabLabel='Tab #1'>My</Text> <Text tabLabel='Tab #2 word word'>favorite</Text> <Text tabLabel='Tab #3 word word word'>project</Text> <Text tabLabel='Tab #4 word word word word'>favorite</Text> <Text tabLabel='Tab #5'>project</Text> </ScrollableTabView>
③ 修改默认样式spa
注意改变下划线颜色,要设置backgroundColor插件
<ScrollableTabView renderTabBar={() => <ScrollableTabBar />} tabBarBackgroundColor='#fff' tabBarActiveTextColor='#b4282d' tabBarInactiveTextColor='#333' tabBarUnderlineStyle={styles.tabBarUnderline} > …………省略 </ScrollableTabView>
tabBarUnderline: { backgroundColor: '#b4282d', height: 2, }
④ 添加数据
因为tab项不少,因此数据写在state里,减小重复代码,也便于修改
constructor(props) { super(props); this.state = { label: ['推荐', '新品', '居家', '餐厨', '配件', '服装', '电器', '洗护', '杂货', '饮食', '婴童', '志趣'], }; }
⑤ 遍历数据
renderScrollableTab() { let label = this.state.label return ( <ScrollableTabView renderTabBar={() => <ScrollableTabBar />} …………省略 > { label.map((item, index) => { return (<Recommend tabLabel={item} key={index}/>) }) } </ScrollableTabView> ) }
注:Recommend 是一个新加的页面,注意要在home.js引入。固然也能够不加新页面,return一个Text也能够。
home.js完整代码 https://github.com/gingerJY/example/blob/master/RN_scrollableTab/home.js
APP首页使用插件常常会出现一些别处没有的问题,这个tab下面内容不显示就是其中之一。解决方法为:
一、加一个是否显示的状态
constructor(props) { super(props); this.state = { tabShow: false, }; }
二、在初始化render以后,将状态设为true
componentDidMount() { setTimeout(() => { this.setState({ tabShow: true }); }, 0) }
三、render的时候判断this.state.tabShow,等setTimeout执行后改变了状态,才会渲染
if (this.state.tabShow){ return ( <ScrollableTabView renderTabBar={() => <ScrollableTabBar />} …………略 > …………略 </ScrollableTabView> ) }
这样就能够显示了。
END--------------------------------------------------
生命周期、布局