我正在將 React 與 TypeScript 一起使用,并且在我可以匯入的目錄中有 5 個 SVG 圖示
import * as OtherIconsGroup from '../src/other-icons';
然后我可以參考每個圖示
<OtherIconsGroup.Loading fill={fillColor} width={size} height={size} />
<OtherIconsGroup.Like fill={fillColor} width={size} height={size} />
<OtherIconsGroup.Copy fill={fillColor} width={size} height={size} />
etc...
現在的問題是我需要向這個目錄添加 30 多個圖示,我正在尋找一種動態渲染所有組件的方法,本質上類似于
{Object.keys(OtherIconsGroup).map(icon => {
return(
<OtherIconsGroup.{icon} fill={fillColor} width={size} height={size} />
)
}
這顯然不起作用,所以我試圖了解如何定義一個組件,給它一個自定義名稱并回傳它。
{Object.keys(OtherIconsGroup).map(icon => {
const IconComponent = `OtherIconsGroup.${icon}`;
return(
<IconComponent fill={fillColor} width={size} height={size}/>
)
}
添加上面的道具時出現以下錯誤,因此尋求在 TypeScript 中正確定義組件的幫助,以便我可以添加 SVG 元素屬性。
Type '{ fill: string; width: number; height: number; }' is not assignable to type 'IntrinsicAttributes'.
Property 'fill' does not exist on type 'IntrinsicAttributes'.ts(2322)
uj5u.com熱心網友回復:
你們真的很親近!JSX 只是輕微的語法問題。
可以這樣做:
const icons = Object.entries(OtherIconsGroup)
.map(([_, Icon]) => <Icon fill={fillColor} width={size} height={size}/>);
或者
const icons = Object.map(OtherIconsGroup)
.map((iconName) => {
const Icon = OtherIconsGroup[iconName];
return <Icon fill={fillColor} width={size} height={size}/>;
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/377279.html
標籤:javascript 反应 打字稿
