[英]How can I match data from an object and pass it as props to another component that displays dynamically?
I am storing my data in JS array.我将我的数据存储在 JS 数组中。 After that I am using map function to display components with specific data.
之后,我使用地图功能来显示具有特定数据的组件。 Until then, everything works.
在那之前,一切正常。 After I click component I want to display a PopUp component that display more specific data from the data.js file.
单击组件后,我想显示一个 PopUp 组件,该组件显示 data.js 文件中的更具体数据。 How can I pass it as props and match correct data to correct component?
如何将它作为道具传递并将正确的数据匹配到正确的组件? At this moment after I click it always shows me the same text.
在我点击后的这一刻,它总是向我显示相同的文本。
My data.js file:我的 data.js 文件:
export const data = {
projects: [
{
name: "Project1",
image: require("../assets/img/Project1.PNG"),
description: "Set number 1",
technologies: "REACT",
link: "github.com",
},
{
name: "Project2",
image: require("../assets/img/Project2.PNG"),
description: "Project number 2 - description",
technologies: "C#",
link: "github.com",
},
This is my PopUp.js that should display more specific data:这是我的 PopUp.js,应该显示更具体的数据:
function Popup({ project, description }) {
return (
<Wrapper>
<p>Project name is: {project}</p>
<p>Description is: {description}</p>
</Wrapper>
);
}
And here I map my data and here is the problem.在这里我映射我的数据,这就是问题所在。 How can I pass it?
我怎样才能通过它?
function Projects() {
const [isOpen, setIsOpen] = useState(false);
const togglePopup = () => {
setIsOpen(!isOpen);
};
return (
<Wrapper>
{data.projects.map((proj) => (
<ProjectContainer background={proj.image} onClick={togglePopup}>
{isOpen && (
<Popup project={proj.name} description={proj.description} />
)}
</ProjectContainer>
))}
</Wrapper>
);
}
Really thanks for all of the answers!真的感谢所有的答案!
You can use index instead of boolean :您可以使用 index 代替 boolean :
function Projects() {
const [isOpen, setIsOpen] = useState('nothing');
return (
<Wrapper>
{data.projects.map((proj, index) => (
<ProjectContainer background={proj.image}
onClick={()=>setIsOpen(oldIndex => index === isOpen ? 'nothing' : index)}>
{isOpen === index && (
<Popup project={proj.name} description={proj.description} />
)}
</ProjectContainer>
))}
</Wrapper>
);
}
The state stores the index of the current opened popup.状态存储当前打开的弹出窗口的索引。
ProjectContainer onClick event check if the current index is the same as their and changes accordingly : to 'nothing' if they are currently opened, to their index if they are not. ProjectContainer onClick 事件检查当前索引是否与它们相同并相应更改:如果它们当前已打开,则为“无”,如果未打开,则为它们的索引。
The condition {isOpen === index && (
is used to show only the current opened popup ie the current index.条件
{isOpen === index && (
用于仅显示当前打开的弹出窗口,即当前索引。
This way you can toggle an individual project and not all of them.通过这种方式,您可以切换单个项目,而不是所有项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.