使用脚手架初始化项目(hkzf-mobile项目名字)
- 使用 npx create-react-app hkzf-mobile
- 进入到项目根目录 使用 npm start
调整后的结构
安装ui组件 阿里的一个antd-mobile 组件库
npm install antd-mobile --save - 导入组件
- 导入样式
// 导入组件
import { Button } from 'antd-mobile';
// 导入样式
import 'antd-mobile/dist/antd-mobile.css'; // or 'antd-mobile/dist/antd-mobile.less'
ReactDOM.render(<Button>Start</Button>, mountNode);
配置路由
-
安装 yarn add react-router-dom
-
导入路由组件:Router / Route / Link
-
在pages文件夹中创建 Home/index.js 和 CityList/index.js 两个组件
-
使用Route组件配置首页和城市选择页面
嵌套路由(★★★) -
嵌套路由:路由内部包含路由
-
用Home组件表示父路由的内容
-
用News组件表示子路由的内容
使用步骤
- 在pages文件夹中创建News/index.js 组件
- 在Home组件中,添加一个Route作为子路由的出口
- 设置嵌套路由的path,格式以父路由path开头(父组件展示了,子组件才会展示)
- 修改pathname为 /home/news,News组件的内容就会展示在Home组件中了
- 安装 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()
}
使用获取到的数据渲染轮播图
// 渲染轮播图的逻辑代码
renderSwipers(){
return this.state.swipers.map(item => (
<a
key={item.id}
href="http://www.itcast.cn"
style={{ display: 'inline-block', width: '100%', height: 212 }}
>
<img
src={`http://localhost:8080${item.imgSrc}`}
alt=""
style={{ width: '100%', verticalAlign: 'top' }}
/>
</a>
))
}
render() {
return (
<div className="index">
<Carousel
autoplay={true}
infinite
autoplayInterval='2000'
>
{/* 调用渲染轮播图的方法 */}
{this.renderSwipers()}
</Carousel>
</div>
)
}