【发布时间】:2021-09-18 00:22:29
【问题描述】:
我正在开发几个组件,我需要在我的组件中显示图标。
假设我的组件的使用代码如下所示:
<SomeComponent
...otherProps
icon=X
/>
我意识到开发人员倾向于以两种方式使用图标:
icon='done'icon={Done}icon={<Done />}icon={doneSvg}
为了更加通用,我创建了这个CustomIcon 组件:
import Icon from '@material-ui/core/Icon';
const CustomIcon = ({ icon }) => {
console.log(icon);
switch (typeof icon) {
case 'object':
if (icon.props) {
return icon;
}
return <>{icon}</>;
case 'function':
return icon()
case 'string':
if (icon.indexOf('svg') > -1) {
return icon;
}
return <Icon>{icon}</Icon>;
default:
return <span>Iconless</span>;
}
}
export default CustomIcon;
但是当我通过 icon={DoneIcon} 并带有以下消息时它失败了:
Error: Objects are not valid as a React child (found: object with keys {$$typeof, type, compare}). If you meant to render a collection of children, use an array instead.
我该如何解决这个问题?
更新
【问题讨论】:
-
什么是 DoneIcon?
-
@iunfixit,在这种情况下,
DoneIcon是import DoneIcon from '@material-ui/icons/Done';
标签: reactjs