![](/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.