Return multiple elements inside React.render()

后端 未结 5 1149
渐次进展
渐次进展 2020-12-04 21:29

I am new in react and I encountered with this problem:

render: function(){
    return (
        

Account

5条回答
  •  一向
    一向 (楼主)
    2020-12-04 22:21

    In React < v16.0 the render method can only render a single root node. (update: this is changed in v16, see below). In your case, you're returning 3 nodes. To get around this you can wrap your 3 nodes in a single root node:

    render: function(){
      return (
        

    Account

    Login Logout
    )}

    In React v16 it's possible for render() to return an array of elements.

    Like with other arrays, you’ll need to add a key to each element to avoid the key warning:

    render() {
      return [
        ,
        ,
        ,
      ];
    }
    

    Another option is to use a Fragment. Fragments let you group a list of children without adding extra nodes to the DOM.

    render() {
      return (
        
          
          
          
        
      );
    }
    

    There is also a short syntax (<>) for declaring fragments:

    render() {
      return (
        <>
          
          
          
        
      );
    }
    

提交回复
热议问题