2016-11-07 50 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

相关问题