我想使用react-feather圖示,但在我創建的標準尺寸按鈕組件中。
要使用 react-feather 組件,我需要像這樣創建它,<Camera size={18} />但是<Icon.Camera size={18} />,我不想繼續重復大小和顏色以及任何其他保持不變的道具。
如何使我的 Button 中的圖示型別動態化。
我知道這個表格是無效的,但我正在尋找一種方式,這是我能寫出的最好的方式來表達我的想法。
import React, { FC } from "react";
import * as Icons from "react-feather";
interface IconProps {
icon?: Icons.Icon;
}
const IconComponent: FC<IconProps> = (props) => {
return (
<button>
{props.icon && <Icons[props.icon] size={18} />}
{props.children}
</button>
);
};
export default IconComponent;
uj5u.com熱心網友回復:
下面的IconComponent組件應該可以。你可以在這個代碼框里看到它。
// Icon.tsx
import React, { ReactNode } from "react";
import { Icon } from "react-feather";
interface IconComponentProps {
icon?: Icon;
children: ReactNode;
}
const IconComponent = ({ icon: FeatherIcon, children }: IconComponentProps) => {
return (
<button>
{FeatherIcon && <FeatherIcon size={18} />}
{children}
</button>
);
};
export default IconComponent;
在那里你可以在任何地方使用它:
// App.tsx
import IconComponent from "./Icon";
import { Camera, Airplay } from "react-feather";
import "./styles.css";
export default function App() {
return (
<div className="App">
<IconComponent icon={Camera}>
<h1>Camera</h1>
</IconComponent>
<IconComponent icon={Airplay}>
<h1>Airlpay</h1>
</IconComponent>
<IconComponent>
<h1>No Icon</h1>
</IconComponent>
</div>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/432127.html
標籤:反应
上一篇:設定單選按鈕之間的狀態
