[英]How to solve element type invalid error in react
我是React的新手,我正在嘗試返回一個通用按鈕組件。 該按鈕應顯示三個不同圖標之一,“DeleteIcon”,“AddIcon”或“EditIcon”。 指定的按鈕類型在IconButton函數的輸入中指定為“buttonType”。
但是我一直得到“react-dom.development.js:24036 Uncaught Invariant Violation:元素類型無效:期望一個字符串”-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>
);
}
icon
已經擁有ReactElement
,只需渲染它。
有關JSX
幕后操作的更多信息,請參閱introduction to JSX
。
此外,您可以使用對象將buttonType
映射到組件:
const ICONS = {
'DeleteIcon': <DeleteIcon />,
'AddIcon': <AddIcon />,
'EditIcon': <EditIcon />
}
export default function IconButton({ handler, text, color, fill, buttonType }) {
return (
<Button onClick={handler} variant={fill ? 'contained' : 'outlined'} color={color}>
{ICONS[buttonType]}
{text}
</Button>
);
}
export default function IconButton({ handler, text, color, fill, buttonType }) {
let Icon;
switch(buttonType) {
// Icon = ...
}
return (
<Button onClick={handler} variant={fill ? 'contained' : 'outlined'} color={color}>
// v render the component
{Icon}
{text}
</Button>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.