我是React的新手,我正在尝试返回一个通用按钮组件。该按钮应该显示三个不同的图标之一,即“ DeleteIcon”,“ AddIcon”或“ EditIcon”。指定的按钮类型在IconButton函数的输入中指定为“ buttonType”。
但是我不断收到“ react-dom.development.js:24036未捕获的不变违规:元素类型无效:预期为字符串”-错误
代码如下:
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;
谢谢!
答案 0 :(得分:2)
您试图在已经是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>
);
}
答案 1 :(得分:1)
router.get('/xyz',(req,res,next)=>{
name = proteinname
session
.run('Match(a:Protein {name:{nameParam}})-[r]->(b:Protein) Return a, b,r LIMIT 10',{nameParam:name})
.then(function(neoresult){
res.send(neoresult)
})
已经拥有icon
,只需对其进行渲染即可。
有关ReactElement
背后的内容的更多信息,请参考introduction to JSX
。
此外,您可以使用对象将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>
);
}