gpt4 book ai didi

reactjs - 如何制作基于对象结构呈现数据的可重用组件?

转载 作者:行者123 更新时间:2023-12-05 05:30:28 27 4
gpt4 key购买 nike

我正在尝试制作一个可重用的 InfoBlock 组件。该组件呈现项目列表。每个项目都有一个标签、图标和值。我不知道如何将可用的 INFO_BLOCK_ITEMS 映射到数据对象并仅呈现数据对象中存在的项目的问题。

所有可用标签和图标的完整列表如下所示:

const INFO_BLOCK_ITEMS = {
author: {
label: "Author",
icon: AccountTreeIcon
},
date: {
label: "Created",
icon: FaceRetouchingNaturalIcon
},
rawMedias: {
label: "RAW Medias",
icon: InsertDriveFileOutlinedIcon
},
face: {
label: "Faces",
icon: ScheduleOutlinedIcon,
faceAction: true,
},
s3Source: {
label: "S3 Source",
icon: AcUnitIcon
}
};

我将数据对象与数据类型一起传递给 InfoBlock 组件(对于另一个页面,数据结构会有所不同,但它将包含来自 INFO_BLOCK_ITEMS 的键:

const DATASET = {
author: "extrauser@site.com",
date: 1669208819,
rawMedias: "Video name 1, Video name 2, Video name 3",
face: ""
};

<InfoBlock data={DATASET} type={"dataset"} />

对于数据对象中的每个键,结果应该是这样的列表:

  <Stack>
<AccountTreeIcon />
<Stack>
<Typography>Author</Typography>
<Typography>extrauser@site.com</Typography>
</Stack>
</Stack>

这是一个带有硬编码列表的 Codesandbox:https://codesandbox.io/s/info-block-forked-0bwrze?file=/src/InfoBlock.tsx

最佳答案

  1. 您不需要将类型传递给 InfoBlock 组件。

  2. Rawmedia类型的数据应该是数字。

  3. 使用图标作为 React 组件。

希望对您有所帮助。

类型:

export type Dataset = {
author: string;
date: number;
rawMedias: string;
face: string;
};

export type RawMedia = {
s3Source: string;
author: string;
date: number;
face: string;
};

信息 block 组件:

const INFO_BLOCK_ITEMS = {
author: {
label: "Author",
icon: <AccountTreeIcon />
},
date: {
label: "Created",
icon: <FaceRetouchingNaturalIcon />
},
rawMedias: {
label: "RAW Medias",
icon: <InsertDriveFileOutlinedIcon />
},
face: {
label: "Faces",
icon: <ScheduleOutlinedIcon />,
action: () => console.log("If no data then button renders")
},
s3Source: {
label: "S3 Source",
icon: <AcUnitIcon />
}
};

interface IInfoBlockProps {
data: Dataset | RawMedia;
}

function InfoBlock({ data }: IInfoBlockProps) {
return(
<Stack gap={"20px"}>
{
Object.keys(data).map((key, _index) => {
const infoBlockItem = INFO_BLOCK_ITEMS[key];
return (
<Stack key={_index} direction={"row"} gap={"10px"}>
{infoBlockItem.icon}
<Stack direction={"row"} gap={"20px"}>
<Typography>{infoBlockItem.label}</Typography>
<Typography>{data[key]}</Typography>
</Stack>
</Stack>
);
})
}
</Stack>
)
}

应用组件:

const DATASET = {
author: "extrauser@example.com",
date: 1669208819.837662,
rawMedias: "Video name 1, Video name 2, Video name 3",
face: ""
};

const RAW_MEDIA = {
s3Source: "https://example.com",
author: "extrauser@example.com",
date: 1669208819.837662,
face: "Some face"
};

function App() {
return (
<div>
<InfoBlock data={DATASET} />
<InfoBlock data={RAW_MEDIA} />
</div>
);
}

关于reactjs - 如何制作基于对象结构呈现数据的可重用组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74661390/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com