2017-04-15 158 views
1

我有一个名为“componentPack”的组件完整的数组。我试图弄清楚如何根据数组中的索引渲染某个组件。给我带来麻烦的部分是在JSX中渲染组件。为了解决我使用所谓的“驿站”中间阵列的问题,我推一个组件,然后从地图:React.js:如何渲染数组中的单个组件?

var comp = stager.map((Component) => { 
    return <Component />; 
}); 

反正有直接从原始阵列挑选一个组成部分?

喜欢的东西:

var comp =() => {return <{componentPack[3][2]} />;} 

我感觉尽管我真的不明白JSX如何在这种情况下。任何帮助是极大的赞赏。

回答

1

您可以直接引用jsx对象。例如,如果你componentPack是组件的这样一个数组:

const componentPack = [1, 2, 3, 4, 5].map((item) => 
    <Component/> 
); 

你可以引用任何单独的元素,并获得特定组件,如:

render(){ 
    return componentPack[2] //Will return the third Component 
} 
1

您可以直接从地图选择条件呈现像

var index = 3; 
const component = componentPack.map((Component, idx) => { 
    if(idx === index) { 
     return <Component/> 
    } else { 
     return null; 
    } 
}) 

成分那么你可以只呈现它像

render() { 
    return (<div>{component}</div>); 
}