簡體   English   中英

如何使用 react 和 typescript 基於道具渲染圖標?

[英]How to render icon based on props using react and typescript?

我正在使用react-feather在組件中呈現圖標。 我可以通過硬編碼讓它導入 static 圖標。但是我如何讓它根據IconLeft.icon道具中傳遞給它的內容呈現圖標?

import { Camera } from 'react-feather';
import React, { FunctionComponent } from 'react';

type HeaderProps = {
    title: string;
    iconLeft?: {
        icon?: string;
        url?: string;
        state?: string;
        label?: string;
    }
}

export const DefaultHeader: FunctionComponent<HeaderProps> = ({ title, iconLeft, iconRight}) => <header>
    <h1>{String}</h1>
    <Camera size={24} stroke-width={2}/>
</header>

您可以使用JSX.Element作為圖標道具的類型。

例子:

type HeaderProps = {
  title: string;
  icon: JSX.Element;
};

const Header: FC<HeaderProps> = ({ icon, title }) => {
  return (
    <header>
      <h1>{title}</h1>
      {icon}
    </header>
  );
};

export default function App() {
  return (
    <div className="App">
      <Header title="header" icon={<Camera />} />
    </div>
  );
}

編輯 throbbing-voice-1uv84w

您可以使用cloneElement通過將其作為道具傳遞來動態呈現您想要的任何組件。

import React, { cloneElement, FunctionComponent } from "react";

type HeaderProps = {
    title: string;
    iconLeft?: {
        icon: JSX.Element;
        url?: string;
        state?: string;
        label?: string;
    };
};

export const DefaultHeader: FunctionComponent<HeaderProps> = ({
    title,
    iconLeft,
}) => (
    <header>
        <h1>{String}</h1>
        {iconLeft && cloneElement(iconLeft.icon, { size: 24, "stroke-width": 2 })}
    </header>
);

使用示例:

<DefaultHeader iconLeft={{ icon: <Camera /> }} />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM