2016-11-07 101 views
0

反應世界令人沮喪......我需要能夠根據某些標準創建標記。例如,我收到一系列物品。我需要檢查這些項目,並根據標準,我需要生成不同的標記。因此,例如,我有一個接收項目數組的函數。如何將JSX元素連接成一個數組?

processItems(itemArray) { 
    // Create an empty array that will hold the final JSX output. 
    let buffer = [] 

    // Somehow push the first required markup into the buffer. 
    buffer.push(<div className"container flex center">); 

    ... here we do a switch statement that evaluates each item in the 'itemArray' argument and based on that I create different <div className="XYZ">{...put stuff here...}</div> markup, which I will push into the buffer - which will contain the final JSX output... 

    // Now I close the initial container element 
    buffer.push(</div>); 

    // And return the buffer for display inside the render() function 
    return buffer; 
} 

的問題是,我不能簡單地做「的Array.push()」個人標記添加到一個數組,因爲反應不喜歡它由於某種原因,我會剛剛結束了jibberish東西,得到顯示。

任何想法我怎麼可能做到這一點?

謝謝。

+2

*「我不能簡單地做‘的Array.push()’個人標記添加到一個數組,因爲反應不喜歡它出於某種原因,「*這是你無法創建一半* DOM元素*的原因。 JSX不是連接* strings *來構建* HTML *,而是創建最終呈現給DOM元素的組件。如果你看看JSX被轉換成什麼,它將有希望變得更有意義。粘貼:'

foo
'在這裏:https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=react&experimental=false&loose=false&spec=false&code=&playground=false。 –

+0

你有沒有得到這個工作?我正在嘗試做類似的事情。在解析器內部,根據JSON對象的內容構建JSX。 – Addinall

回答

15

您的解決方案應該是這樣的:

processItems(itemArray) { 
    // Create an empty array that will hold the final JSX output. 
    let buffer = [] 

    buffer.push(<div>A</div>); 
    buffer.push(<div>B</div>); 
    buffer.push(<div>C</div>); 


    // And return the buffer for display inside the render() function 
    return (
     <div className"container flex center"> 
      {buffer} 
     </div> 
    ); 
} 

JSX不是HTML,你不能裝配在多個步驟的HTML元素。

+1

是的,我的解決方案確實看起來像最後一樣,在render()函數中,我在div之間顯示{buffer}。但我認爲我的問題就是你指出的,我希望/希望通過首先將內容推入數組來組裝最終的輸出/ html。這顯然不可能。唉...... – pentool

+0

我猜我不明白的是,在render()中我可以使用任意數量的HTML元素來顯示,只要它們位於最外面的div之間即可。在這個概念中,爲什麼我不能簡單地將所有這些HTML元素放入一個變量或一個數組中,並將其顯示在最外面的div中?這基本上就是我想要做的。 – pentool

+0

@pentool你可以。 – zerkms

0

這樣做:

var albumId=this.state.albumId; 
var albumCaption=this.state.albumCaption; 
var rows = []; 
var cols = []; 
var that=this; 
this.state.photos.forEach(function(photo,index) { 
    const element = <td key={photo.PhotoID}> 
         <PhotoFrame> 
          <a href={'/#/details/' + photo.PhotoID + '/' + albumId + '/' + albumCaption}> 
           <img src={'/Handler/Index/PhotoID=' + photo.PhotoID +'/Size=M'} alt=""/> 
          </a> 
         </PhotoFrame> 
         <p> 
          {albumCaption} 
         </p> 
        </td>; 
     cols = [...cols, element]; 
     if ((index+1)%5===0 || index===that.state.photos.length-1){ 
      const row = <tr key={photo.PhotoID.toString() + "_"}>{cols}/tr> 
      rows = [...rows, row]; 
      cols=[]; 
     } 
    }); 

... 

<Col md={12}> 
    <table> 
     <tbody> 
      <tr> 
       {rows} 
      </tr> 
     </tbody> 
    </table> 
</Col> 

代碼從www.sireus.se

相關問題