简体   繁体   English

根据输入动态导入 React 组件

[英]Dynamically import React Components based on input

I want to render different Components based on some checkboxes selection pattern without having to import components that may not be used.我想根据某些复选框选择模式呈现不同的组件,而不必导入可能不会使用的组件。

I have an Array which contains the Component names (I used numbers as an example) and I want to import each component based on the values of the array.我有一个包含组件名称的数组(我以数字为例),我想根据数组的值导入每个组件。

I came up with something like this:我想出了这样的事情:


import {Suspense} from 'react'


export default function CreationForm() {

 const docs = [1,3,5]

  return (
      <Suspense fallback={<div>Loading...</div>}>
        {
          docs.map(val => React.lazy(() => import(`documents/${val}.jsx`)))   
        }
      </Suspense>
  )

}

I know this solution does not work but I think it explains what I am trying to do.我知道这个解决方案不起作用,但我认为它解释了我想要做什么。

I could try using state but the actual "docs array" is an state variable in the real application so it could cause duplicated state.我可以尝试使用 state 但实际的“文档数组”是实际应用程序中的 state 变量,因此它可能导致重复的 state。

I did this as a test and worked:我这样做是为了测试并工作:

  const A = React.lazy(() => import(`documents/1.jsx`))
  ...
  *** SNIP ***
  ...
      <Suspense fallback={<div>Loading...</div>}>
        {
          docs.map((val) => <A/>)   
        }
      </Suspense>

But I cannot dynamically import each component like this.但我不能像这样动态导入每个组件。

Ok, so you don't need conditional imports, you just want to do conditional rendering.好的,所以你不需要条件导入,你只想做条件渲染。 That's waaaaay simpler.这更简单。

Example:例子:

import { FormA } from "./FormA";
import { FormB } from "./FormB";

const MyComponent = ({ which }) => {
    return <>
        {which === "form-a" && <FormA />}
        {which === "form-b" && <FormB />}
    <>;
};

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

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