下面的代码实现了上面图片的功能
javascript
import React, { useMemo } from "react";
import "./HomeHead.less";
import Img from "../assets/images/timg.jpg";
const HomeHead = function HomeHead(props) {
{ /*父组件传过来的值 */}
let { today } = props;
{ /*处理时间缓存在状态未改变时是否走暖存,useMemo和vue中计算属性功能类似*/ }
{ /*用useMemo,只有在today变化时,才重新执行time函数,而在更新组件HomeHead时,today未改变,则不执行time函数, today的值走的是缓存和vue的计算属性原理一样*/}
let time = useMemo(() => {
//过滤处理时间格式*
// console.log('@', today.match(/^\d{4}(\d{2})(\d{2})$/))
let [, month, day] = today.match(/^\d{4}(\d{2})(\d{2})$/);
let area = [
"",
"一",
"二",
"三",
"四",
"五",
"六",
"七",
"八",
"九",
"十",
"十一",
"十二",
];
return {
day,
month: area[+month] + "月",
};
}, [today]);
return (
<header className="home-head-box">
{/*头部左边 */}
<div className="info">
<div className="time">
<span>{time.day}</span>
<span>{time.month}</span>
</div>
<h2 className="title">海鸥移动端博客</h2>
</div>
{/*头部右边 */}
<div className="pictture">
<img src={Img} alt="头像" />
</div>
</header>
);
};
export default HomeHead;
javascript
import React, { useState, useEffect } from "react";
import HomeHead from "../components/HomeHead";
import _ from "../assets/utils"; // 工具函数库,处理时间 formatTime函数
import { Swiper } from "antd-mobile"; // UI组件
import { Link } from "react-router-dom";
import "./Home.less";
import api from "../api";
const Home = () => {
//创建时间状态 ,_.formatTime(null,'{0}{1}{2}{4}:{5}')当前时间作为初始时间值
let [today, setToday] = useState(_.formatTime(null, "{0}{1}{2}"));
// console.log(_.formatTime(null,'{0}{1}{2}{4}:{5}'));
// 轮播图数据
let [bannerData, setBannerData] = useState([]);
// 第一次渲染完毕,请求后台数据,useEffect不能用async修饰,所有里面包一层使用立马执行函数
useEffect(() => {
(async () => {
try {
// const newData = await api.queryNewsLatest();
// console.log(newData);
let { date, stories, top_stories } = await api.queryNewsLatest();
// 更新时间日期
setToday(date);
// 更新bannerData状态
setBannerData(top_stories);
} catch (_) {}
})();
}, []);
return (
<div className="home-box">
{/*today抓给子组件,头部组件*/}
<HomeHead today={today} />
{/*轮播图*/}
<Swiper autoplay={true} loop={true} className="swiper-box">
{bannerData.length > 0
? bannerData.map((item) => {
let { image, id, hint, title } = item;
return (
<Swiper.Item key={id}>
<Link
to={{
pathname: `/detail/${id}`,
}}
>
<img src={image} alt="" />
<div className="desc">
<h3 className="title">{hint}邓紫棋</h3>
<p className="author">{title}邓紫棋牛逼</p>
</div>
</Link>
</Swiper.Item>
);
})
: null}
</Swiper>
{/*列表*/}
</div>
);
};
export default Home;