先看App運行效果:
輪播圖.gif
react-native中有專門實現(xiàn)輪播圖的模塊Swiper,和引入React的方式一樣,通過import方式引入:
import Swiper from 'react-native-swiper';
輪播圖上方的標題'狗狗的家',用Text控件實現(xiàn).由于render方法中不能同時返回多個控件,所以需要將Swiper和Text通過一個View來封裝.
render() {
let H = 200;
if (this.state.isShow) {
return(
<View style={{height: H, alignItems:'center', backgroundColor:'blue'}}>
<Swiper autoplay = {true} height = {H} showsPagination = {true} dotColor="white"
activeDotColor='yellow' horizontal={true}>
{
this.state.items.map((item, index) => {
console.log(item, index)
//cover: 等比例放大; center:不變; contain:不變; stretch:填充;
return (<Image style={{height: H, width:ScreenWidth}} key = {index} resizeMode='cover' source={{uri: item}}/>)
})
}
</Swiper>
<Text style={styles.title}>
狗狗的家
</Text>
</View>
);
}else {
return(
<View style={{height:H, width: ScreenWidth, backgroundColor:'green'}}/>
);
}
}
輪播圖中的狗,貓,熊三張圖片都是通過網(wǎng)絡異步加載,通過添加isShow屬性來對網(wǎng)絡加載結(jié)果進行不同渲染,請求成功后,才進行Swiper控件的渲染.
constructor(props){
super(props);
this.state = {
isShow: false,
items:[]
}
}
其中items用來存放圖片的地址.
在componentDidMount方法中添加圖片地址,并通過setState方法,重新調(diào)用控件的render方法:
componentDidMount() {
var item;
for (let i = 0; i < 3; i++){
switch (i){
case 0:{
item = 'http://blogdailyherald.com/wp-content/uploads/2013/04/382065_560557460633306_930109857_n.jpg';
break;
}
case 1:{
item = 'http://img0.pclady.com.cn/pclady/pet/choice/cat/1701/6.jpg';
break;
}
default:{
item = 'https://gss0.baidu.com/9fo3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/3812b31bb051f819dc048662dbb44aed2e73e7f1.jpg';
break;
}
}
this.state.items.push(item);
}
console.log(this.state.items + '111');
this.setState({
isShow: true,
items: this.state.items
})
}
詳細請參看Demo
喜歡和關(guān)注都是對我的支持和鼓勵~