如何将 material-ui 图标作为 props 传递给 React 组件并渲染它?

huangapple go评论95阅读模式
英文:

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

这是我通常的做法:

  1. import React from 'react';
  2. import AppsOutageIcon from '@mui/icons-material/AppsOutage';
  3. const AnotherComponent = (props) => (
  4. <div>
  5. 这是我传递的图标{props.icon}
  6. </div>
  7. );
  8. function App() {
  9. return (
  10. <div className="App">
  11. <AnotherComponent icon={<AppsOutageIcon />} />
  12. </div>
  13. );
  14. }

如果将导入的图标直接作为属性传递给另一个组件并尝试渲染它,将会遇到以下错误:

  1. 对象无法作为 React 子元素(找到的是带有键 {$$typeof, type, compare} 的对象)。如果您的意思是渲染子元素集合,请改用数组。

要解决这个问题,您需要首先通过将导入的图标包装为标签的方式实例化组件,如<AppsOutageIcon />,而不仅仅使用 AppsOutageIcon

英文:

Here is how I usually do it:

  1. import React from &#39;react&#39;;
  2. import AppsOutageIcon from &#39;@mui/icons-material/AppsOutage&#39;;
  3. const AnotherComponent = (props) =&gt; (
  4. &lt;div&gt;
  5. Here is my passed icon: {props.icon}
  6. &lt;/div&gt;
  7. );
  8. function App() {
  9. return (
  10. &lt;div className=&quot;App&quot;&gt;
  11. &lt;AnotherComponent icon={&lt;AppsOutageIcon /&gt;} /&gt;
  12. &lt;/div&gt;
  13. );
  14. }

If you pass the imported icon directly as a prop to another component and try to render it, you will encounter the following error:

  1. 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 &lt;AppsOutageIcon /&gt;, instead of just using AppsOutageIcon.

huangapple
  • 本文由 发表于 2023年5月25日 14:34:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76329493.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定