While you could pass in state and setter from the parent App
component, it doesn't make a lot of sense for your example.
I would try to keep the Popup
component more generic.
In the example below the Popup
component manages its own UI state (opened/closed), but all the content is passed in as props.
import React, { useState } from "react";
import "./styles.css";
const data = [
{
title: "Customer Focus title",
content: "Customer Focus content",
src: "https://picsum.photos/200",
alt: "Fog",
coreValue: "Customer Focus"
},
{
title: "Persistence title",
content: "Persistence content",
src: "https://picsum.photos/200/300?grayscale",
alt: "Grey Mountains",
coreValue: "Persistence"
}
];
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{data.map(({ title, content, src, alt, coreValue }) => (
<Popup
title={title}
content={content}
src={src}
alt={alt}
coreValue={coreValue}
/>
))}
</div>
);
}
interface Props {
title: string;
content: string;
src: string;
alt: string;
coreValue: string;
}
function Popup({
title = "",
content = "",
src = "",
alt = "",
coreValue = ""
}: Props) {
const [showDetails, setShowDetails] = useState(false);
return (
<>
<figure onClick={() => setShowDetails(true)}>
<img src={src} alt={alt} />
<figcaption>{coreValue}</figcaption>
</figure>
{showDetails && (
<section>
<h4>{title}</h4>
<p>{content}</p>
<button onClick={() => setShowDetails(false)}>Close 2</button>
</section>
)}
</>
);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…