首页模块
目标
- 能够使用Carousel组件完成轮播图功能
- 能够安装axios,并且使用axios进行网络请求
- 能够使用Flex组件完成TabBar功能
- 能够知道轮播图与TabBar出现的bug,并且解决
- 能够安装Sass,编写Sass代码
- 能够使用Grid组件完成租房小组功能
- 能够利用H5 API获取当前的定位信息
- 能够使用百度地图API展示地图页面,获取对应城市信息
轮播图(★★★)
组件使用的基本步骤
- 打开antd-mobile组件库的Carousel组件文档
- 选择基本,点击 (
</>
) 显示源码 - 拷贝核心代码到Index的组件中
- 分析并且调整代码,让其能够在项目中运行
轮播图的移植
-
拷贝示例代码中的内容
- 导入组件
import { Carousel, WingBlank } from 'antd-mobile';
- 状态
state = { // 图片的名称 data: ['1', '2', '3'], // 图片的高度 imgHeight: 176, }
- 声明周期钩子函数,修改状态,设置数据
componentDidMount() { // simulate img loading setTimeout(() => { this.setState({ data: ['AiyWuByWklrrUDlFignR', 'TekJlZRVCjLFexlOCuWn', 'IJOtIlfsYdTyaDTRVrLI'], }); }, 100); }
- 结构
<div className="index"> <Carousel {/* 自动播放 */} autoplay={false} {/* 无限循环 */} infinite {/* 轮播图切换前的回调函数 */} beforeChange={(from, to) => console.log(`slide from ${from} to ${to}`)} {/* 轮播图切换后的回调函数 */} afterChange={index => console.log('slide to', index)} {/* 自动切换的时间 */} autoplayInterval='2000' > {/* 遍历状态里面的数据,创建对应的a标签和img图片标签 */} {this.state.data.map(val => ( <a key={val} href="http://www.alipay.com" style={ { display: 'inline-block', width: '100%', height: this.state.imgHeight }} > <img src={`https://zos.alipayobjects.com/rmsportal/${val}.png`} alt="" style={ { width: '100%', verticalAlign: 'top' }} {/* 图片加载完成的时候调用 */} onLoad={() => { // fire window resize event to change height window.dispatchEvent(new Event('resize')); this.setState({ imgHeight: 'auto' }); }} /> </a> ))} </Carousel> </div>
-
现在我们需要对轮播图进行定制
- 先优化相应的结构,删除不必要的代码
<div className="index"> <Carousel autoplay={true} infinite autoplayInterval='2000' > {this.state.data.map(val => ( <a key={val} href="http://www.alipay.com" style={ { display: 'inline-block', width: '100%', height: this.state.imgHeight }} > <img src={`https://zos.alipayobjects.com/rmsportal/${val}.png`} alt="" style={ { width: '100%', verticalAlign: 'top' }} /> </a> ))} </Carousel> </div>
获取轮播图的数据
- 安装 axios: yarn add axios
- 在Index组件中导入axios
import axios from 'axios'
- 在state中添加轮播图数据:swipers
state = {
// 轮播图状态
swipers: [],
}
- 新建一个方法 getSwipers 用来获取轮播图数据
async getSwipers() {
// 请求数据
let {data: res} = await axios.get('http://localhost:8080/home/swiper')
// 判断返回的状态是否是成功
if(res.status!= 200){
console.error(res.description)
return
}
// 把获取到的值设置给state
this.setState({
swipers: res.body
})
}
- 在componentDidMount钩子函数中调用这个方法
componentDidMount() {
// 调用请求轮播图的方法
this.getSwipers()
}