[英]How to change dynamically the render of icons inside a table based on a type of the data coming
由于我是 React 的新手,因此我在制作一个功能组件时遇到了一些困难,该组件基本上应该根据从数据中获取的类型动态更改图标的呈现。
表本身已经存在,它被映射并获取我需要的所有数据。
在一行/单元格中,我必须包含一个传递类型的 Icon 组件,并且我还需要在此处使用onClick
功能
<TableCell>
<Icon rowType={row.type} onClick={<some function>}/>
</TableCell>
row.type
是我得到的特定数据的一种类型,我需要关注 2 种类型
基于这 2 种类型,我必须在表中呈现一个 SLOT_ICON 和一个 SITE_ICON,当我连续拥有这两个类型之一时。
我想制作一个if/elseif
但我实际上不知道如何呈现以及如何根据我单击的图标包含 onClick 事件。
伪代码示例:
const Icon = rowType => {
if (rowType === 'SLOT') {
SLOT;
} else if (rowType === 'SITE') {
SITE;
}
<-- onClick logic somewhere here? -->
return Icon
};
您可以在反应中使用条件渲染。
const Icon = ({ type, onClick }) => {
if (type === "SLOT") return <img src={"slot"} onClick={onClick} />;
else if (type === "SITE") return <img src={"site"} onClick={onClick} />;
else return <img src={"icon"} onClick={onClick} />;
};
您可以使用Icon
如下
<Icon type="SLOT" onClick={() => {}} />
一般的想法是,您最终可能会遇到这样的事情(请注意,我对您的代码做了很多假设,因此您可能需要调整提供的示例):
import React, { useCallback } from 'react';
import TableCell from '/path/to/component/';
import Icon from '/path/to/component/';
const ParentComponent = ({row, ...props}) => {
//...
const onIconClick = useCallback(() => {
//do whatever you have to do
}, [ /*dependencies*/ ]);
return (
<TableCell>
<Icon rowType={row.type} onClick={onIconClick} />
</TableCell>
);
}
import React, { useMemo, useCallback } from 'react';
const Icon = ({rowType, onClick}) => {
const iconData = useMemo(() => {
const basePath = '/path/to/image/folder/';
switch (rowType) {
case 'SLOT':
return {
src: basePath + 'slotFile.ext',
alt: 'slot alternative text'
};
case 'SITE':
return {
src: basePath + 'siteFile.ext',
alt: 'site alternative text'
};
default:
return null;
}
}, [rowType]);
const handleClick = useCallback(() => {
// 1. do whatever additional operation you have to do (if any)
// ...
// 2. execute the function passed by the parent
onClick();
}, []);
return iconData ? (
<img
src={iconData.src}
alt={iconData.alt}
onClick={() => handleClick()}
/>
) : null;
}
export default Icon;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.