Is there a way to render multiple React components in the React.render() function?

后端 未结 8 1210
无人共我
无人共我 2020-12-08 06:33

For example could I do:

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

React.render( 
  

        
相关标签:
8条回答
  • 2020-12-08 07:07

    Just wrap your multiple components into single tag. For example:

    React.render(
      <div>
        <PanelA />
        <PanelB />
      </div>, 
      document.body  
    );
    
    0 讨论(0)
  • 2020-12-08 07:07

    Prior to React 16, multiple top-level elements in the same render() would require you to wrap everything in a parent element (typically a <div>):

    render () {
      return (
        <div>
          <Thing1 />
          <Thing2 />
        </div>
      )
    }
    

    React 16 introduced the ability to render an array of top-level elements (with a warning that they all must have unique keys):

    render () {
      return ([
        <Thing1 key='thing-1' />,
        <Thing2 key='thing-2' />
      ])
    }
    

    React 16.2 introduced the <Fragment> element, which functions exactly like the <div> in the first example but doesn't leave a pointless parent <div> hanging around the DOM:

    import React, { Fragment } from 'react'
    
    ...
    
    render () {
      return (
        <Fragment>
          <Thing1 />
          <Thing2 />
        </Fragment>
      )
    }
    

    There's a shorthand syntax for it, but it isn't supported by most tooling (e.g., syntax highlighters) yet:

    import React from 'react'
    
    ...
    
    render () {
      return (
        <>
          <Thing1 />
          <Thing2 />
        </>
      )
    }
    
    0 讨论(0)
提交回复
热议问题