问题:react-native-swiper
的宽度和高度怎么设置?
本文我们将用设置高度来举例说明(宽度的设置可以类比得到)
目标:给Swiper
设置300的高度
初尝试使用react-native-swiper
的同学都知道,react-native-swiper
的高度很魔性。先贴一张官方给的设置截图:

尝试去理解If no specify default fullscreen mode by flex:1
的意思。
表面上看,就是如果不设置,就会按照通过flex:1
设置高度。所以很自然就想到,给Swiper
指定一个高度即可,于是我做了以下尝试:
render() {
return (
<View style={{flex:1, backgroundColor: 'gray'}}>
<Swiper
style={{backgroundColor: 'yellow'}}
height={300}>
<View style={{backgroundColor: 'green', height: 150}}><Text>1</Text></View>
<View style={{backgroundColor: 'green', height: 150}}><Text>2</Text></View>
<View style={{backgroundColor: 'green', height: 150}}><Text>3</Text></View>
<View style={{backgroundColor: 'green', height: 150}}><Text>4</Text></View>
</Swiper>
</View>
)
}
然后你会发现,结果并没有你认为的那样,看下面的截图。

然后再仔细品味这句description,可能你会想到,设置flex:0
就好了
,于是把上面的设置修改一下,给Swiper
的style
设置flex:1
,信心满满地保存运行查看效果。

通过看颜色可以知道,Swiper
的灰色背景确实只有300高,但是Swiper
的点却在最下方,说明Swiper
仍然占据了整个屏幕的宽度。
当然,你也可以尝试在Swiper
的style
中设置高度,这里就不贴代码了,我直接给出我测试的结论。Swiper
设置的属性height
,会直接覆盖style中的height
,也就是说,如果只设置style中的height
,则style中height
生效,如果同时设置style中的height
和Swiper的属性height
,则Swiper的属性height
生效,style中的height
无论设置什么值都没有效果。
不管是style
中的height
还是Swiper
的属性height
都只是限制了Swiper
的背景色高度,而不是Swiper
占据的整个空间的高度。
通过上面的实验,仔细分析你就会发现,无论怎样设置,Swiper
的高度始终等于屏幕的高度,而它的本质是等于Swiper
父组件的高度(当然,这里的结论是基于Swiper
的父组件只有Swiper
一个子组件,如果有其他组件,那就会根据flex:1
来分享父组件剩余的空间)。
到这里,已经快要接近真相了,假设我们给Swiper
包裹一层View
作为父组件(后面简称父组件),然后设置父组件的高度,那么理论上Swiper
就会自适应父组件,使得Swiper
的高度等于父组件的高度。
于是写下代码,做最后的试验
render() {
return (
<View style={{flex:1, backgroundColor: 'gray'}}>
<View style={{height: 300}}>
<Swiper>
<View style={{backgroundColor: 'green', height: 150}}><Text>1</Text></View>
<View style={{backgroundColor: 'green', height: 150}}><Text>2</Text></View>
<View style={{backgroundColor: 'green', height: 150}}><Text>3</Text></View>
<View style={{backgroundColor: 'green', height: 150}}><Text>4</Text></View>
</Swiper>
</View>
</View>
)
}

所以最终方案为:在Swiper
外面包裹一层View
,通过设置View
的高度,间接设置Swiper
的高度。如下所示:
<View style={{height: 300}}>
<Swiper>
//...item省略
</Swiper>
</View>
网友评论