我是 React 新手,我想返回一个通用按钮组件。该按钮应该显示三个不同图标之一,“DeleteIcon”、“AddIcon”或“EditIcon”。指定的按钮类型在 IconButton 函数的输入中指定为“buttonType”。
但是我不断收到“react-dom.development.js:24036 Uncaught Invariant Violation: Element type is invalid: expected a string”-error
代码如下:
import React from 'react';
import Button from '@material-ui/core/Button';
import DeleteIcon from '@material-ui/icons/Delete';
import AddIcon from '@material-ui/icons/Add';
import EditIcon from '@material-ui/icons/Edit';
export default function IconButton({ handler, text, color, fill, buttonType }) {
let Icon;
switch (buttonType) {
case 'DeleteIcon':
Icon = <DeleteIcon />;
break;
case 'AddIcon':
Icon = <AddIcon />;
break;
case 'EditIcon':
Icon = <EditIcon />;
break;
default:
return null;
}
return (
<Button onClick={handler} variant={fill ? 'contained' : 'outlined'} color={color}>
<Icon />
{text}
</Button>
);
}
import React from 'react';
import GithubComponent from '../components/GithubComponent';
import IconButton from '../components/buttons/IconButton';
import Button from '../components/buttons/Button';
const LandingPage = () => (
<div>
<IconButton text="Hello!" color="red" fill="contained" buttonType="DeleteIcon" />
</div>
);
export default LandingPage;
谢谢!
最佳答案
你正试图在一个已经是 JSX 的变量中使用 JSX。
改变
return (
<Button onClick={handler} variant={fill ? 'contained' : 'outlined'} color={color}>
<Icon /> // Trying to render a component that is already a react element
{text}
</Button>
);
到
return (
<Button onClick={handler} variant={fill ? 'contained' : 'outlined'} color={color}>
{Icon} // Rendering the react element
{text}
</Button>
);
或者您可以做的是获取开关中的元素,然后使用 JSX 渲染它。
export default function IconButton({ handler, text, color, fill, buttonType }) {
let Icon;
switch (buttonType) {
case 'DeleteIcon':
Icon = DeleteIcon; // Only getting the Component
break;
case 'AddIcon':
Icon = AddIcon; // Only getting the Component
break;
case 'EditIcon':
Icon = EditIcon; // Only getting the Component
break;
default:
return null;
}
return (
<Button onClick={handler} variant={fill ? 'contained' : 'outlined'} color={color}>
{Icon && <Icon />} // You can pass any prop to the component here
{text}
</Button>
);
}
关于javascript - React中元素类型无效错误如何解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57871012/