react项目搭建

使用脚手架初始化项目(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>
    )
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值