需求:当页面中存在一个收藏图片,初始状态是未收藏,点击后显示收藏状态,于此同时父组件存在一个按钮,按钮的状态会跟随子组件中收藏未收藏的状态的改变而改变。同时实现取消收藏的效果。
效果:
父组件:
import React, { useRef, useState } from "react";
import Son from "./son";
const Father = () => {
const [parentData, setParentData] = useState<String>("未收藏");
const getChildData = (val: String) => {
setParentData(val);
};
return (
<div className="home-wrap">
<button >{parentData}</button>
<Son getCollection={getChildData} />
</div>
);
};
export default Father;
子组件:
import React, { useState } from 'react';
import before from "../img/a.png";
import after from "../img/b.png"
const Son = (props: any) => {
const { getCollection } = props;
const [collection, setCollection] = useState<String>("未收藏");
const handleClick = (val: String) => {
setCollection(val);
getCollection(val);
};
return (
<div className="child-wrap">
<div >
{
collection === "未收藏" ? (
<div onClick={() => handleClick("已收藏")}><img style={{ width: "50px" }} src={before} /></div>
) : collection === "已收藏" ? (
<div onClick={() => handleClick("未收藏")}>
<div onClick={() => handleClick("未收藏")}><img style={{ width: "50px" }} src={after} /></div>
</div>
) : collection === "未收藏" ? (
<div onClick={() => handleClick("已收藏")}><img style={{ width: "50px" }} src={before} /></div>
) : null
}
</div>
</div>
);
};
export default Son;