英文:
How to pass material-ui icons to react component as props and render it?
问题
我创建了一个React应用,并使用Material Icons对其进行了样式化,但不知道如何将这个图标作为属性传递给另一个组件。我已经知道如何将字符串、数组和对象作为属性传递给组件。
我尝试将其作为字符串传递,但不起作用,然后尝试解决这个问题。
英文:
I created a react app and styled it using material icons, but don't know how to pass this icon as props to another component. I already know how to pass string, array and objects as props to components.
I tried to pass this as strings but didn't work and tried to resolve this issue.
答案1
得分: 0
这是我通常的做法:
import React from 'react';
import AppsOutageIcon from '@mui/icons-material/AppsOutage';
const AnotherComponent = (props) => (
<div>
这是我传递的图标:{props.icon}
</div>
);
function App() {
return (
<div className="App">
<AnotherComponent icon={<AppsOutageIcon />} />
</div>
);
}
如果将导入的图标直接作为属性传递给另一个组件并尝试渲染它,将会遇到以下错误:
对象无法作为 React 子元素(找到的是带有键 {$$typeof, type, compare} 的对象)。如果您的意思是渲染子元素集合,请改用数组。
要解决这个问题,您需要首先通过将导入的图标包装为标签的方式实例化组件,如<AppsOutageIcon />
,而不仅仅使用 AppsOutageIcon
。
英文:
Here is how I usually do it:
import React from 'react';
import AppsOutageIcon from '@mui/icons-material/AppsOutage';
const AnotherComponent = (props) => (
<div>
Here is my passed icon: {props.icon}
</div>
);
function App() {
return (
<div className="App">
<AnotherComponent icon={<AppsOutageIcon />} />
</div>
);
}
If you pass the imported icon directly as a prop to another component and try to render it, you will encounter the following 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.
To resolve this issue, you need to instantiate the component first by wrapping the imported icon as a tag, like <AppsOutageIcon />
, instead of just using AppsOutageIcon
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论