简体   繁体   English

反应动态组件类型示例

[英]react dynamic component type example

How/Where can i add types to the dynamic component Icons[name] ?如何/在哪里可以将类型添加到动态组件Icons[name]

import * as Icons from "react-icons/fa";

const DynamicFaIcon = ({ name }: any) => {
  const IconComponent = Icons[name];

  return <IconComponent />;
};

在此处输入图像描述

You could just grap the keys from the import, since its a JS object like any other:您可以从导入中获取密钥,因为它与其他任何一样都是 JS object:

import * as Icons from "react-icons/fa";

const DynamicFaIcon = ({ name }: {name: keyof typeof Icons}) => {
  const IconComponent = Icons[name];

  return <IconComponent />;
};

I would be careful about importing literally everything from that package though.不过,我会小心地从 package 中导入所有内容。 There's over 1,500 components in there, does any application actually make use of all of them?那里有超过 1,500 个组件,是否有任何应用程序实际使用了所有这些组件? You'll end up bundling way more than you need.你最终会捆绑比你需要的更多的方式。

This is my answer on dynamic icons problem, is it your question answer??这是我对动态图标问题的回答,这是你的问题答案吗?? , maybe it will help you, use it like this ` ,也许它会帮助你,像这样使用它`

import React from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {library} from '@fortawesome/fontawesome-svg-core';
import * as Icons from '@fortawesome/free-solid-svg-icons';

const iconList = Object.keys(Icons)
    .filter((key) => key !== 'fas' && key !== 'prefix')
    .map((icon) => Icons[icon]);

library.add(...iconList);

const Feature = ({ carFeature }) => {
    console.log(carFeature);
    return (
        <div>
            <FontAwesomeIcon icon={carFeature?.icon} color="#ddd" />
            <h3>{carFeature?.name}</h3>
            <p>{carFeature?.desc}</p>
        </div>
    );
};
export default Feature;

If no then try this如果没有,那么试试这个

Not the OP's direct issue but for users encountering this error for libraries not under their control, one can suppress this error is by adding:不是 OP 的直接问题,而是对于不受其控制的库遇到此错误的用户,可以通过添加来抑制此错误:

{
  ...
  "suppressImplicitAnyIndexErrors": true,
  ...
}

to the tsconfig.json file.到 tsconfig.json 文件。

Read more here Question Answer在这里阅读更多问题答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM