简体   繁体   English

如何在 React 中动态导入组件?

[英]How to dynamically import a component in React?

I am trying to optimize a component of mine with dynamic rendering, but I'm facing some issues, so this is my current situation:我正在尝试使用动态渲染优化我的组件,但我遇到了一些问题,所以这是我目前的情况:

I have an Alert component that renders an alert message, along with an icon.我有一个Alert组件,它呈现警报消息以及一个图标。

I have a Icons module, which is a library of icons我有一个Icons模块,它是一个图标库

I am currently rendering the icon as follows (this is not actual code, it's just to give the idea):我目前正在渲染图标如下(这不是实际代码,只是为了给出想法):

import * as icons from '../icons';
import DefaultIcon from '../icons';

function Alert(iconName='defaultIcon', message) {  

  function getIcon(iconName) {
    if (iconName === 'defaultIcon') {
      return DefaultIcon()
    }
    return icons[iconName]
  }

  return (
    <div>
      <span>{getIcon(iconName)}</span>
      <span>{message}</span>
    </div>

  )
}

So, suppose Alert gets called without iconName most of the times, so the components doesn't need to import all of the icons at all.所以,假设大多数时候Alert在没有iconName的情况下被调用,所以组件根本不需要导入所有的图标。

I would like to avoid including all of the icons in the Alert component by default, but only doing so if iconName is specified我想避免在默认情况下将所有图标包含在Alert组件中,但只有在指定iconName时才这样做

Is it even possible to do so?甚至有可能这样做吗?

I don't think it's possible this way.我不认为这是可能的。

Maybe create a component for the Icon that imports the icon libary.也许为导入图标库的图标创建一个组件。 In the Alert component you could implement the Icon component as a child:在 Alert 组件中,您可以将 Icon 组件实现为子组件:

<Alert message="Alert!">
  <Icon iconName="defaultIcon" />
</Alert>

You should import icons dynamically with type or name etc. something like below.您应该使用类型或名称等动态导入图标,如下所示。

import React from 'react';

export default function Icon({ type, ...props }) {
  const Icon = require(`./icons/${type}`).default;

  return <Icon {...props} />
}

import Icon from './Icon';

<Icon type="addIcon" />

Ok, looks like I managed, and that's how I did it:好的,看起来我成功了,我就是这样做的:

import DefaultIcon from '../icons';

function Alert(message, iconName="") {
  const [icon, useIcon] = useState();

  //componentDidMount
  const useEffect(() => {
    //if an icon name is specified, import the icons
    if (iconName) {
      import("./icons").then(icons => setIcon(icons[iconName]))
    } else {
      setIcon(DefaultIcon)
    }
  }
  ,[])
  
  return (
    <span>{icon}</span>
    <span>{message}</span>
  )
}

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

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