前言
最近,在我复刻抖音的时候,有个功能困扰了我两天,就是如何在纵向布局的基础上实现横向布局,就像我们平常在写盒子布局一样,如:我们有3个盒子纵向(列)分布,然后每个盒子内部的盒子横向(行)分布。
困惑
就比如抖音,我们在刷视频的时候是上下滑动的,而进入or退出用户个人主页的时候是左右滑动的,那么如何实现呢?
理想状态
理想状态是上面的效果,我试着模仿view写法,代码如下:
import React from 'react';
import { View, Text } from 'react-native';
import PagerView from 'react-native-pager-view';
const TestDrawer = ({ navigation }) => {
return (
<PagerView style={{flex:1}}>
{/* 纵向的PagerView,用于管理视频页面的切换 */}
<PagerView style={{ flex: 1 }} orientation="vertical">
{/* 视频页面1和用户主页1 */}
<PagerView style={{ flex: 1 }} orientation="horizontal">
{/* 视频页面1 */}
<View style={{ flex: 1, backgroundColor: 'black' }}>
{/* 在这里放置视频1的内容 */}
<Text style={{ color: 'white' }}>视频1</Text>
</View>
</PagerView>
{/* 视频页面2和用户主页2 */}
<PagerView style={{ flex: 1 }} orientation="horizontal">
{/* 视频页面2 */}
<View style={{ flex: 1, backgroundColor: 'black' }}>
{/* 在这里放置视频2的内容 */}
<Text style={{ color: 'white' }}>视频2</Text>
</View>
</PagerView>
{/* 视频页面3和用户主页3 */}
<PagerView style={{ flex: 1 }} orientation="horizontal">
{/* 视频页面3 */}
<View style={{ flex: 1, backgroundColor: 'black' }}>
{/* 在这里放置视频3的内容 */}
<Text style={{ color: 'white' }}>视频3</Text>
</View>
</PagerView>
</PagerView>
</PagerView>
);
};
export default TestDrawer;
效果图:
如图,只能上下滑动视频,而添加的主页无法打开
原因
PagerView不支持该类嵌套
解决方案
我们可以在纵向分布的PagerView外部增加一个View,这样的话每个视频都会共用一个页面,效果大致如图:
这样的话,刚好也满足了性能要求,无需重复渲染每个视频的个人主页数据,效果如下:
代码如下:
import React from 'react';
import { View, Text } from 'react-native';
import PagerView from 'react-native-pager-view';
const TestDrawer = ({ navigation }) => {
return (
<PagerView style={{flex:1}}>
{/* 纵向的PagerView,用于管理视频页面的切换 */}
<PagerView style={{ flex: 1 }} orientation="vertical">
{/* 视频页面1和用户主页1 */}
<PagerView style={{ flex: 1 }} orientation="horizontal">
{/* 视频页面1 */}
<View style={{ flex: 1, backgroundColor: 'black' }}>
{/* 在这里放置视频1的内容 */}
<Text style={{ color: 'white' }}>视频1</Text>
</View>
</PagerView>
{/* 视频页面2和用户主页2 */}
<PagerView style={{ flex: 1 }} orientation="horizontal">
{/* 视频页面2 */}
<View style={{ flex: 1, backgroundColor: 'black' }}>
{/* 在这里放置视频2的内容 */}
<Text style={{ color: 'white' }}>视频2</Text>
</View>
</PagerView>
{/* 视频页面3和用户主页3 */}
<PagerView style={{ flex: 1 }} orientation="horizontal">
{/* 视频页面3 */}
<View style={{ flex: 1, backgroundColor: 'black' }}>
{/* 在这里放置视频3的内容 */}
<Text style={{ color: 'white' }}>视频3</Text>
</View>
</PagerView>
</PagerView>
{/* 第二个页面:用户主页 */}
<View style={{ flex: 1, backgroundColor: 'gray' }}>
{/* 在这里放置用户主页的内容 */}
<Text style={{ color: 'white' }}>通用用户主页</Text>
</View>
</PagerView>
);
};
export default TestDrawer;
如图的代码就是新增的
好了,以上就是今天分享的全部内容了,谢谢观看!