繁体   English   中英

从对象渲染React组件

[英]Rendering React Components from an Object

假设我有以下将组件作为条目的对象:

import Comp1 from './Comp1'
import Comp2 from './Comp2'
import Comp3 from './Comp3'

const components = { 'comp1' : Comp1, 'comp2' : Comp2, 'comp3' : Comp3 }

我想使用此对象来呈现这些组件:

Object.keys(components).map((key, i) => (

    <div key={i}> 
        <components[key] /> // this does not work
    </div>
))}

实际上,我正在尝试使用配置对象渲染路线:

export const routes =   {

'home' : {  
    path: '/', 
    component: Home,
    exact: true,
    access: {
        anonymous: true
    },
    navigation: {
        label: 'Home',
        icon: 'fa-home',
        show: true
    }
},

....

const Routes = () => (

    <div>

        {Object.keys(routes).map((k, i) => (

            <Route 
                key={i} 
                exact={routes[k].exact} 
                path={routes[k].path} 
                render={() => 

                    !routes[k].access.anonymous ? ( 

                        <Redirect to="/login"/>  

                    ) : ( 

                        <routes[k] /> // nope
                    )
                } 
            />

        ))}

    </div>
)

我当时以为<components[key] />是JSX,而React不需要使用JSX,所以解决方案可能是使用标准JS在使用JSX的情况下呈现这些组件。 虽然我不确定该怎么做。

routes[k]不是React组件, routes[k].component是。 另外,由于您仅对值感兴趣,因此请使用Object.values而不是Object.keys

Object.values(routes).map((route, i) => (
    <Route key={i} 
           exact={route.exact} 
           path={route.path} 
           render={() => 
              !route.access.anonymous ? ( 
                  <Redirect to="/login"/>  
              ) : ( 
                  <route.component /> 
              )
          } 
      />
  ))

工作实例

暂无
暂无

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

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