reactjs 如何通过变量加载React组件?

osh3o9ms  于 2023-02-15  发布在  React
关注(0)|答案(1)|浏览(187)

我在一个文件“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>
    )
  }
}
xeufq47z

xeufq47z1#

你可以创建一个包含多个组件的对象,它的关键字应该是你在属性中传递的名称,比如

const allComponents = {
  newBuilding: NewBuilding,
  barracks: Barracks,
}
        
class BuildingContent extends React.Component {
  let name = this.props.content.name;
  let Building = allComponents[name];
            
  render() {
    return (
      <div className='building-content-wrapper'>
        <Building />
      </div>
    )
  }
}

相关问题