簡體   English   中英

React:循環渲染組件

[英]React: rendering components in a loop

map所有文檔都使用花括號,但是下面的代碼和我在處理React時看到的大多數示例都使用括號。 我試圖確切地找出區別和代碼在做什么。

使用花括號時,除非我專門添加return ,否則不會呈現任何內容。 所以我認為括號是某種內聯函數,可以自動返回或React轉換結果並將其內聯到JSX中?

// Renders fine
render()
{
   return (
      <div className="item-list">
         {
            this.props.items.map(
               ( _item, _index ) => (
               <ItemComponent
                  key={ _index }
                  name={ _item.name }
                  description={ _item.description }
               />
            ) )
         }
      </div>
   );
}

// Nothing
render()
{
   return (
      <div className="item-list">
         {
            this.props.items.map(
               ( _item, _index ) => 
               {
                  <ItemComponent
                     key={ _index }
                     name={ _item.name }
                     description={ _item.description }
                  />
               } )
         }
      </div>
   );
}

// Renders fine
render()
{
   return (
      <div className="item-list">
         {
            this.props.items.map(
               ( _item, _index ) => 
               {
                  return <ItemComponent
                     key={ _index }
                     name={ _item.name }
                     description={ _item.description }
                  />
               } )
         }
      </div>
   );
}

與React無關,全部與javascript有關

大括號表示它是一個函數體,因此我們需要手動使用return關鍵字

 this.props.items.map(
               ( _item, _index ) => 
               { // Note: represent function body, normal javascript function
                  <ItemComponent
                     key={ _index }
                     name={ _item.name }
                     description={ _item.description }
                  />
               } )

根據arrow functions ,因此具有隱式返回行為,因此如果是單行表達式,則需要明確提及。

render()
{
   return (
      <div className="item-list">
         {
            this.props.items.map(
               ( _item, _index ) => ( // Note: single line expression, so impilicit;y return our ItemComponent
               <ItemComponent
                  key={ _index }
                  name={ _item.name }
                  description={ _item.description }
               />
            ) )
         }
      </div>
   );
}

因此,箭頭函數中的括號返回一個值,在執行多行代碼時使用了花括號,而不僅是簡單的返回,因此需要手動返回語句,因為javascript無法知道返回的那幾行。

materials.map(material => ({key:material.name})); 

返回一個對象

materials.map(material => {
   let newMat = material.name+'_new'; 
   return newMat;
}); 

我們需要返回,因為我們正在執行1行或多行操作並嘗試返回最終結果

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM