Typescript和React-渲染组件会引发错误

时间:2020-09-02 15:53:08

标签: javascript reactjs typescript

我正在尝试将UI材料中的图标注入到另一个组件并进行渲染,但是会引发错误

import InsertCommentIcon from "@material-ui/icons/InsertComment";

const Siderbar = () => {
  return (
      <SidebarOption icon={InsertCommentIcon} title="Threads" />
  );
};

export default Siderbar;
import React from "react";
import "./SidebarOption.css";

interface SidebarOptionProps {
  icon?: React.ReactNode;
  title: string;
  id?: string;
}



const SidebarOption: React.FC<SidebarOptionProps> = ({ icon, title, id }) => {
  return (
    <div className="sidebarOption">

      {icon ? (
        <h3> {icon}{title}</h3>
      ) : (
          <h3 className="sidebarOption__channel">
            <span className="sidebarOption__hash">#</span>
            {title}
          </h3>
        )
      }
    </div >
  );
};

export default SidebarOption

错误消息:

Error: Objects are not valid as a React child (found: object with keys {$$typeof, type, compare, displayName, muiName}). If you meant to render a collection of children, use an array instead.
    in h3 (at SidebarOption.tsx:15)
    in div (at SidebarOption.tsx:12)
    in SidebarOption (at Sidebar.tsx:50)
    in div (at Sidebar.tsx:39)

可以在React中做到这一点,但是我对Typescript还是很陌生。

有任何线索吗?

1 个答案:

答案 0 :(得分:3)

您需要使用标签来传递组件。

 <SidebarOption icon={<InsertCommentIcon />} title="Threads" />