首页 > 解决方案 > 通过 props 传递的组件的 React 和 TypeScript 使用

问题描述

我有一个组件,它通过道具Sidebar将唯一图标传递给子组件。SidebarRow

import SidebarRow from './SidebarRow';
import {
    CogIcon,
    UsersIcon
} from '@heroicons/react/solid';

const Sidebar: React.FC = () => {
    return (
        <div className="p-2 mt-5 max-w-5xl xl:min-w-lg">
            <SidebarRow src="" title="Tom Mc" />
            <SidebarRow Icon={UsersIcon} title="Friends" />
            <SidebarRow Icon={CogIcon} title="Account" />
        </div>    
    )
}

export default Sidebar;

SidebarRow组件中,接口定义了传入的道具。在这里,我尝试有条件地渲染图像或图标,具体取决于传入的内容。

import React from "react";

interface SidebarRowProps {
    src?: string
    Icon?: React.FC
    title: string
};

const SidebarRow: React.FC<SidebarRowProps> = ({ src, Icon, title }) => {
    return (
        <div className="">
            {src && (
                <img className="rounded-full" src={src} alt="" width="30" height="30" />            
            )}
            {Icon && (
                <Icon className="h-8 w-8 text-blue-500" />
            )}
            <p className="hidden sm:inline-flex font-medium">{title}</p>
        </div>    
    )
};

export default SidebarRow;

我收到组件className属性的以下错误Icon

Type '{ className: string; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.
  Property 'className' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.ts(2322)
(JSX attribute) className: string

如何定义 Icon 类型以便 className 属性不会引发此错误?

谢谢!

标签: reactjstypescript

解决方案


以下代码工作正常

import React from "react";

interface SidebarRowProps {
    src?: string
    Icon?: React.ComponentType<React.SVGProps<SVGSVGElement>>
    title: string
};


推荐阅读