我在一个文件“buildings.js”中导出了多个组件,为了简单起见,我只给予一个基本示例
export const NewBuilding = () => {
return (
<div className="wrapper">New Building</div>
)
}
export const Barracks = () => {
return (
<div className="wrapper">Barracks</div>
)
}
另一个组件通过 prop 获取特定的建筑组件名称。我需要渲染名称与 prop 中的名称匹配的建筑。
class BuildingContent extends React.Component {
getComponent = () => {
var name = this.props.content.name;
// Here I want to access the component by variable
// Like <Buildings[name] /> or anything similar that works.
// This obviously doesn't work
//return <Buildings.Name />
return <Buildings.Barracks />
}
render() {
return (
<div className='building-content-wrapper'>
// Hardcoded for functionality
<Buildings.NewBuilding />
</div>
)
}
}
1条答案
按热度按时间xeufq47z1#
你可以创建一个包含多个组件的对象,它的关键字应该是你在属性中传递的名称,比如