- 刷新页面轮播图不会自动播放
- 切换tabBar轮播图高度出现问题
解决方案
轮播图数据加载完毕后再去渲染轮播图
import React from "react";
import { Carousel, Flex } from "antd-mobile";
import axios from "axios";
import Nav1 from "../../assets/images/nav-1.png";
import Nav2 from "../../assets/images/nav-2.png";
import Nav3 from "../../assets/images/nav-3.png";
import Nav4 from "../../assets/images/nav-4.png";
import "./index.css";
const navs = [
{
id: 1,
img: Nav1,
title: "整租",
path: "/home/list",
},
{
id: 2,
img: Nav2,
title: "合租",
path: "/home/list",
},
{
id: 3,
img: Nav3,
title: "地图找房",
path: "/map",
},
{
id: 4,
img: Nav4,
title: "去出租",
path: "/rent/add",
},
];
export default class Index extends React.Component {
state = {
swiperList: [],
imgHeight: 203,
swiperLoaded: false,
};
async getSwiperList() {
const { data: res } = await axios.get("http://localhost:8080/home/swiper");
console.log(res);
if (res.status !== 200) {
return console.log("获取轮播图数据失败");
}
this.setState(() => {
return {
swiperList: res.body,
swiperLoaded: true,
};
});
}
renderSwiper() {
return this.state.swiperList.map((val) => (
<a
key={val.id}
href="www.baidu.com"
style={{
display: "inline-block",
width: "100%",
height: this.state.imgHeight,
}}
>
<img
src={`http://localhost:8080${val.imgSrc}`}
alt=""
style={{ width: "100%", verticalAlign: "top" }}
/>
</a>
));
}
renderNav() {
return navs.map((item) => {
return (
<Flex.Item className="navItem" key={item.id}>
<img src={item.img} alt="" />
<div>{item.title}</div>
</Flex.Item>
);
});
}
componentDidMount() {
this.getSwiperList();
}
render() {
return (
<div>
<div className="swiper">
{this.state.swiperLoaded ? (
<Carousel autoplay autoplayInterval={3000} infinite>
{this.renderSwiper()}
</Carousel>
) : (
""
)}
</div>
<Flex className="nav">{this.renderNav()}</Flex>
</div>
);
}
}
相关代码截图如下



本文介绍了在React应用中使用Ant Design的轮播图组件遇到的两个问题:一是页面刷新后轮播图不会自动播放,二是切换TabBar时轮播图高度出现异常。为了解决这些问题,提出了在轮播图数据加载完成后渲染组件的策略,并附上了相关代码截图。
494

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



