有没有办法在React.render()函数中呈现多个React组件? [英] Is there a way to render multiple React components in the React.render() function?

查看:696
本文介绍了有没有办法在React.render()函数中呈现多个React组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我可以这样做:

import React from 'react';
import PanelA from './panelA.jsx';
import PanelB from './panelB.jsx';

React.render( 
  <PanelA />
  <PanelB />, 
  document.body  
);

React将呈现:

body
   PanelA
   PanelB

目前我得到错误:

Adjacent JSX elements must be wrapped in an enclosing tag

使用browserify和babelify进行转换

while transpiling with browserify and babelify

推荐答案

自React v16.0版本发布以来,当您在组件内部时,您可以渲染一个组件数组,而不会将项目包装在一个额外的元素中:

Since the React v16.0 release you can render an array of components without wrapping items in an extra element when you are inside a component:

render() {
  return [
    <li key="one">First item</li>,
    <li key="two">Second item</li>,
    <li key="three">Third item</li>,
    <li key="four">Fourth item</li>,
  ];
}

请记住只设置密钥。

ReactDOM.render 中,您仍然无法呈现多个项目,因为react需要root。因此,您可以在 ReactDOM.render 中呈现单个组件,并在内部组件中呈现项目数组。

In the ReactDOM.render you still can't render multiple items because react needs a root. So you can render a single component inside the ReactDOM.render and render an array of items in the internal component.

这篇关于有没有办法在React.render()函数中呈现多个React组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆