这可能是一个完整的noob问题,但我无法解决这个问题。我有一个React组件,并且在其渲染方法中,我想渲染一些动态传入的组件(通过道具)。使用.map渲染多个React组件
这是我从渲染方法(ES6,与巴贝尔transpiled)
return (
<div className={openState}>
/* Shortened for brevity*/
{this.props.facets.map(function(f) {
var CompName = facetMap[f.type]
return <CompName key={f.id} />
})}
/* Shortened for brevity*/
</div>
)
facetMap
是一个简单的映射为一个字符串匹配与传入的“类型”的回报。我似乎无法得到要在页面上实际呈现的组件。
我将.map()方法的结果存储在var中,然后将其记录到控制台,并显示了一个组件数组。但render方法中的{facetComponents}
具有相同的结果。
编辑,为有志于解决
因为我真的找不到任何地方的答案,这是我的完整的解决方案,这要归功于@Mathletics
//Components imported using ES6 modules
import OCFacetText from "./oc-facet-text"
// Etc...
//Later on, in my render method:
let facetMap = {
"text": OCFacetText,
"number": OCFacetNumber,
"numberrange": OCFacetNumberRange,
"boolean": OCFacetBoolean,
"checkbox": OCFacetCheckbox,
// Etc, etc...
}
let facetComps = facets.map(function(f) {
var CompName = facetMap[f.type]
return <CompName key={f.id} />
})
//Finally, to render the components:
return (
<div className={openState}>
/* Shortened for brevity*/
{facetComps}
/* Shortened for brevity*/
</div>
)
如果你只呈现一个组件工作的呢? – Mathletics
只需在页面上呈现组件?是的,这是有效的。基本上用例是允许这些组件被重用和动态指定。 –
“facetMap”是一组字符串还是一组Component类? [动态组件名称](http://stackoverflow.com/questions/29875869)在SO上已被很好地覆盖。 – Mathletics