React轮播图使用
使用react-native开发的移动端的项目往往有轮播图的存在,尤其是首页,如果正确使用轮播图,下面有一些简单的步骤。
- 在项目的终端运行
npm i react-native-swiper --save命令安装轮播图组件 - 在要使用轮播图的页面中导入轮播图组件
import Swiper from 'react-native-swiper'; - 其中,在Swiper身上,
showsPagination={false}是用来控制页码的;showsButtons={false}是用来控制左右箭头显示与隐藏;height={160}是用来控制轮播图区域的高度的! - 设置轮播图的样式:
var styles = StyleSheet.create({
wrapper: {},
slide1: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#9DD6EB', },
slide2: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#97CAE5', },
slide3: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#92BBD9', },
image:{ width:'100%', height:'100%' }})
- 将组件的代码结构引入到页面上
<Swiper style={styles.wrapper} showsButtons={true} height={160} autoplay={true}>
<View style={styles.slide1}>
<Image source={{uri:'http://www.itcast.cn/images/slidead/BEIJING/2017410109413000.jpg'}} style={styles.image}></Image>
</View>
<View style={styles.slide2}>
<Image source={{uri:'http://www.itcast.cn/images/slidead/BEIJING/2017440109442800.jpg'}} style={styles.image}></Image>
</View>
<View style={styles.slide3}>
<Image source={{uri:'http://www.itcast.cn/images/slidead/BEIJING/2017441409442800.jpg'}} style={styles.image}></Image>
</View>
</Swiper>
接口请求轮播图的数据并在相应的地方挂载展示出来的案例
export default class Home extends Component{
constructor(props){
super(props)
this.state = {
lunbotu:[] //轮播图数组
}
}
// 请求轮播图的数据,在View挂载之前,所以是使用componentWillMount
componentWillMount(){
fetch('http://vue.studyit.io/api/getlunbo') //使用接口url请求数据
.then(res=>res.json()) //将数据转换成json类型
.then(data=>{ //将获得到的数据(轮播图的图片等信息)挂载到相应的地方
// console.warn(JSON.stringify(data, null, ' '))
this.setState({
lunbotu: data.message
})
})
}
render() {
return ( <View>
{/* 轮播图的结构 */}
{/* 在 轮播图的 Swiper 组件外面,需要套一层 View,给这个 View 需要手动设置一个高度 */}
<View style={{ height: 220 }}>
<Swiper style={styles.wrapper} showsButtons={true} autoplay={true} loop={true}>
{this.state.lunbotu.map((item, i) => { //像vue中的for一样展示请求到的数据
return <View key={i}>
<Image source={{ uri: item.img }} style={{ width: '100%', height: '100%' }}></Image>
</View>
})}
</Swiper>
</View>
具体更详细的api,请参见react轮播图使用api
本文介绍了在React项目中实现轮播图的步骤,包括安装轮播图组件、导入并配置组件、设置样式以及通过接口获取数据进行展示。详细API参考可进一步查阅。

891

被折叠的 条评论
为什么被折叠?



