在web移动端一般会有这样的需求,实现上中下三栏布局(上下导航栏位置固定,中间部份内容超出可滚动),以下图所示:react
实现方法以下:web
HTML结构:布局
<div class='container'> <div class='header'></div> <div class='content'></div> <div class='footer'></div> </div>
首先能够利用fixed或者absolute定位,实现简单。flex
如今介绍另一种方法——利用-wekkit-box/flex,实现上下两栏固定高度,中间高度自适应的布局。spa
CSS代码以下:code
使用-webkit-box:blog
.container{ width: 100%; height: 100%; display: -webkit-box; -webkit-box-orient: vertical; } .header{ height: 200px; background-color: red; } .content{ -webkit-box-flex: 1; overflow: auto; } .footer{ height: 200px; background-color: blue; }
使用flex:it
.container{ width: 100%; height: 100%; display: flex; flex-direction: column; } .header{ height: 200px; background-color: red; } .content{ flex: 1; overflow: auto; } .footer{ height: 200px; background-color: blue; }
实际应用中应该将以上两种放在一块儿写,这里只是为了下文而将新旧两种写法分开。 io
在react native中,实现样式只是CSS中的一个小子集,其中就使用flex的布局class
实现的思路和上面也是相同的,不过因为react native中对于View组件而言,overflow属性只有'visible'和'hidden'两个值( 默认是'hidden' ),并无可滚动的属性,所以中间内容部分须要使用"ScrollView"滚动容器
组件渲染:
render(){ return( <View style={styles.container}> <View style={styles.header}></View> <ScrollView style={styles.content}> </ScrollView> <View style={styles.footer}></View> </View> ); }
样式:
const styles = StyleSheet.create({ container: { flex: 1,
flexDirection: 'column' }, header: { height: 100, backgroundColor: 'red', }, content: { flex: 1, }, footer: { height: 100, backgroundColor: 'blue', } });
效果:
react native最基础的布局就实现了。
因为react native中布局方法基本就这两种: flex和absolute布局,掌握了flex布局,也就基本搞定了。