在实际开发中, 经常会遇到轮播图, 轮播图的数据通常情况下都是网络获取的. 这里简单的记录一下接口获取轮播图数据, 然后动态赋值给 swiper.
轮播图组件是通过 react-native-swiper
实现, 这里不再多说.
直接源码说明:
export default class MainPage extends Component {
static navigationOptions = {
headerTitle: '首页',
};
constructor(props) {
super(props);
this.state = {
bannerData: null,
}
};
componentDidMount() {
this.fetchData();
}
render() {
return (
<View style={styles.container}>
<ScrollView style={styles.container}>
<View style={styles.cycle_view}>
{
this.state.bannerData == null ?
<View style={styles.slide}/>
:
<Swiper
style={styles.swiper}
height={width/720*407}
loop={true}
autoplay={true}
autoplayTimeout={3}
horizontal={true}
paginationStyle={{bottom: 10}}
showsPagination={false}>
{this.renderSwiper()}
</Swiper>
}
</View>
</ScrollView>
</View>
);
};
//请求数据
fetchData() {
NetRequest.get('你的接口 url地址',null,null).then((response) => {
this.setState({
bannerData: response['data']
})
}, (error) => {
Alert.alert('error')
})
};
// 渲染
renderSwiper(){
var itemArr = [];
for (var i = 0; i < this.state.bannerData.length; i++) {
let data = this.state.bannerData[i];
itemArr.push(
<TouchableOpacity key={i}>
<Image source={{uri: data['imagePath']}} style={styles.swiper_image} />
</TouchableOpacity>
);
}
return itemArr;
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: color.view_background,
flex: 1,
},
cycle_view: {
height: width/720*407,
},
slide: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#9DD6EB',
},
swiper: {
},
swiper_image: {
height: width/720*407,
},
});
其实很简单, 就是通过请求的数据来动态的创建每一个 swiperItem !
react-native 小白交流群: 860196537 或者 234713941
enjoy it!