Javascript 如何在渲染函数中返回多个组件?

Javascript 如何在渲染函数中返回多个组件?,javascript,reactjs,Javascript,Reactjs,我制作了三个组件:蝙蝠组件、保龄球组件、野战组件。我正在向每个组件传递道具。当字符串与bat、field或bowl匹配时,该特定组件将呈现并显示在网页上。我在返回中返回{renderData} 代码: 以上代码不起作用如何在renderData中添加其他组件 如果我使用renderData=它可以工作,但是如果我这样做->renderData=它不工作,为什么? renderData = ( <div> <Fieldcomponent prop1 =

我制作了三个组件:蝙蝠组件、保龄球组件、野战组件。我正在向每个组件传递道具。当字符串与bat、field或bowl匹配时,该特定组件将呈现并显示在网页上。我在返回中返回{renderData}

代码:

以上代码不起作用如何在renderData中添加其他组件

如果我使用renderData=它可以工作,但是如果我这样做->renderData=它不工作,为什么?

renderData = (
  <div>
     <Fieldcomponent 
     prop1 = this.props.type.name
     prop2 = this.props.matches
     prop3 = this.props.email
     />
     <Pie prop1 = this.props.type.name/>
  </div>
)
但是,我可能会建议进一步清理代码

render(){
  return(
    <div>
    { 
      this.props.type === 'bat' ? <Bat {...props} /> :
      this.props.type === 'bowl' ? <Bowl {...props} /> :
      this.props.type === 'field' ? <Field {...props} /> : <Default {...props} />
    }
    </div>
  )
}

此代码不起作用,因为相邻的JSX元素必须包装在一个封闭的标记中

React 16引入的片段,它允许您包装JSX表达式,而无需添加额外的div

如果您使用的是React 16,请使用片段:

如果您没有使用React 16,请将它们包装在一个div中:


处理这一问题的最佳方法是将一种哈希表设置为一个包含多个组件的对象,这样可以根据需要进行扩展,因此可以是

const components = {
  bat: BatComponent,
  bowl: BowlComponent,
  field: FieldComponent
}
现在制作一个函数,该函数将选择要显示的正确组件

renderComponent(){
  const { type, ...restProps } = this.props;
  const Component = components[type]
  return <Component {...restProps } />
}

如果需要返回两个组件,最好将这两个组件包装成一个组件,并将其添加到包含组件哈希表的对象中


请参阅exp.

将RenderData包装在div中或片段您说将其包装在div中,但作为回报,我将其包装在div中我的问题与此不同,为什么我要在div中添加多个组件,因为我在return中添加RenderData我简化了代码,因为组件可以有任意数量的组件;如果您使用在别处定义的可重用组件,效果会更好。通过定义任何JSX组件,您都需要将其包含在div标记中,而不管您是在render、renderData还是其他方式中设置它。-这就是创建片段的原因,因为React仍然为您呈现一个div。
render(){
  return(
    <div>
    { 
      this.props.type === 'bat' ? <Bat {...props} /> :
      this.props.type === 'bowl' ? <Bowl {...props} /> :
      this.props.type === 'field' ? <Field {...props} /> : <Default {...props} />
    }
    </div>
  )
}
 if (this.props.type === "bat") {
      renderData = (
        <React.Fragment>
          <Batcomponent
          prop1={this.props.type.name}
          prop2={this.props.matches}
          prop3={this.props.email}
        />
        <Pie prop1={this.props.type.name}/>
        </React.Fragment>
    )
   }else if ...
 if (this.props.type === "bat") {
      renderData = (
        <div>
          <Batcomponent
          prop1={this.props.type.name}
          prop2={this.props.matches}
          prop3={this.props.email}
        />
        <Pie prop1={this.props.type.name}/>
        </div>
    )
   }else if ...
const components = {
  bat: BatComponent,
  bowl: BowlComponent,
  field: FieldComponent
}
renderComponent(){
  const { type, ...restProps } = this.props;
  const Component = components[type]
  return <Component {...restProps } />
}
render(){
  return {this.renderComponent()}
}
const CompA = ({ children }) => {
  return (
    <div>
      <h3>Im component A</h3>
      {children}
    </div>
  );
};