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

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

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 &#39;react&#39;;
import AppsOutageIcon from &#39;@mui/icons-material/AppsOutage&#39;;

const AnotherComponent = (props) =&gt; (
  &lt;div&gt;
    Here is my passed icon: {props.icon}
  &lt;/div&gt;
);

function App() {
  return (
    &lt;div className=&quot;App&quot;&gt;
      &lt;AnotherComponent icon={&lt;AppsOutageIcon /&gt;} /&gt;
    &lt;/div&gt;
  );
}

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 &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:

确定