要呈现的React返回组件数组未正确嵌套

时间:2018-01-29 18:10:45

标签: javascript reactjs react-native jsx

我的React组件渲染方法中有以下代码

    add(book: IBook, authorId: string): Promise<IBookModel> {
         let groupSetup: IGroupModel = new Group({...group});
         newBook.createInitialSetup();
         let bookReady = {... newBook};

         return this.bookRepository.add(bookReady)
                    .then((completedBook: IBookModel) => {
                        return this.bookRepository.findAuthorById(authorId)
                                   .then((author: IAuthorModel) => {
                                        let newBookAuthor: IAuthorModel = new Author();
                                         newBookAuthor(completedBook._id, author._id);

                                        let finalBookAuthor = {... newBookAuthor} as IAuthor;

                                        return this.bookRepository.addBookAuthor(finalBookAuthor)
                                                    .then((result: IBookAuthorModel) => {
                                                           return completedBook;
                                         });                  
                        });
         });
    }

但是,这两个div render: function() { return ( <div> <div>div1</div> <div>div2</div> {this.getOtherDivs()} </div> ); }, getOtherDivs: function() { return ([ <div>div3</div>, <div>div4</div> ]); }, div3嵌套在单个数组中,而不是分开。

当我为最顶级的div做child.length时,我得到3而不是4。

我不想将最后两个div包装在一个封闭的div中。

3 个答案:

答案 0 :(得分:3)

尝试使用<React.Fragment />

getOtherDivs: function() {
   return (
     <>
       <div>div3</div>
       <div>div4</div>
     </>       
   );
},

答案 1 :(得分:0)

使用map循环数组并将div直接返回到主div

render: function() {
    return (
       <div>
           <div>div1</div>
           <div>div2</div>
           {this.getOtherDivs().map(item => item)}
       </div>
    );
},

答案 2 :(得分:0)

您可以使用map

执行此操作

声明一个项目数组:

const items = [div3, div4];

现在,您的渲染方法应如下所示:

render() {
    return (
       <div>
           <div>div1</div>
           <div>div2</div>
           {this.items.map(item => <div>{item}</div>)}
       </div>
    );
}

如果您有一个对象数组,那么您可以这样做:

声明一个数组数组:

const items = [[div3, div4],[div5, div6],[div7, div8]];

然后在你的渲染方法中:

render() {
    return (
       <div>
           <div>div1</div>
           <div>div2</div>
           {this.items.map(item => 
               <div>
                   <div>item[0]</div>
                   <div>item[1]</div>
               </div>
           )}
       </div>
    );
}