Javascript 使用json模式呈现react组件

Javascript 使用json模式呈现react组件,javascript,reactjs,webpack,Javascript,Reactjs,Webpack,我正在尝试使用JSON动态呈现React组件。我的文件夹结构如下所示: components Foo.jsx Bar.jsx index.js App.jsx import Foo from './Foo' import Bar from './Bar' export default { 'FOO': Foo, 'BAR': Bar } import React from 'react' import ComponentsMap from './component

我正在尝试使用JSON动态呈现React组件。我的文件夹结构如下所示:

components
   Foo.jsx
   Bar.jsx
   index.js
App.jsx
import Foo from './Foo'
import Bar from './Bar'

export default {
  'FOO': Foo,
  'BAR': Bar
}
import React from 'react'
import ComponentsMap from './components'

const json = {'type': 'BAR', props: {}} 
const App = () => {
   const ComponentToRender = ComponentsMap[json.type]
   return (
      <ComponentToRender {...json.props} />
   )
}
index.js
中,我将所有组件导出为字符串,以便使用它们在
App.jsx
中进行渲染。看起来是这样的:

components
   Foo.jsx
   Bar.jsx
   index.js
App.jsx
import Foo from './Foo'
import Bar from './Bar'

export default {
  'FOO': Foo,
  'BAR': Bar
}
import React from 'react'
import ComponentsMap from './components'

const json = {'type': 'BAR', props: {}} 
const App = () => {
   const ComponentToRender = ComponentsMap[json.type]
   return (
      <ComponentToRender {...json.props} />
   )
}
我的
App.jsx
如下所示:

components
   Foo.jsx
   Bar.jsx
   index.js
App.jsx
import Foo from './Foo'
import Bar from './Bar'

export default {
  'FOO': Foo,
  'BAR': Bar
}
import React from 'react'
import ComponentsMap from './components'

const json = {'type': 'BAR', props: {}} 
const App = () => {
   const ComponentToRender = ComponentsMap[json.type]
   return (
      <ComponentToRender {...json.props} />
   )
}
从“React”导入React
从“./components”导入组件映射
const json={'type':'BAR',props:{}
常量应用=()=>{
const componentorender=ComponentsMap[json.type]
返回(
)
}

在我的方法中,每次添加新组件时,我都必须将其导出到
index.js
中。还有其他方法吗?

试试巴贝尔的通配符插件。它将导入目录中存在的所有文件。然后,您就不需要index.jsx,通过App.jsx内的*导入所有组件


希望这能对您有所帮助。

无论何时创建新组件,您都需要导出它(一种或另一种方式)。组件将需要显式导出,否则
webpack
(或任何其他绑定程序)将不知道如何解析其部分。