![](/img/trans.png)
[英]How to render the icon based on the prop using react and 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>
);
}
您可以使用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.