簡體   English   中英

如何使用 typescript 在 React 中動態創建 JSX 標簽?

[英]How do i dynamically create JSX tag in React using typescript?

我想動態導入反應圖標

這適用於 Javascript,但我如何將其轉換為 Typescript 而不會出現各種錯誤?

代碼:

import * as ReactIcons from 'react-icons/all';
const getIcon = (icon) => {
  const TagName = ReactIcons[icon];
  return <TagName />;
};

這是來自 react-icons 的 output 文件,如果有幫助的話:

// node_modules/react-icons/all.d.ts
export * from './fa';
export * from './fa';
export * from './io';
export * from './md';
export * from './ti';
export * from './go';
export * from './fi';
export * from './gi';
export * from './gi';
export * from './gi';

你可以這樣做:

import * as ReactIcons from 'react-icons/all';

type GetIconProps = {
  icon: keyof typeof ReactIcons;
}

const getIcon = ({icon}: GetIconProps) => {
  const TagName = ReactIcons[icon];
  return <TagName />;
};

// Example
getIcon({icon: keyof typeof ReactIcons})

甚至更短:

const getIcon = ({ icon }: GetIconProps) => {
  const TagName = ReactIcons[icon];
  return <TagName />;
};

必須說它感覺有點hacky,所以會嘗試直接從 package 導入。

暫無
暫無

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

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