简体   繁体   English

如何将JSX元素连接成一个数组?

[英]How to concatenate JSX elements into an array?

Frustrating times in React world... I need to be able to create markup based on certain criterias. 在React世界中令人沮丧的时候......我需要能够根据某些标准创建标记。 For example, I receive an array of items. 例如,我收到一系列项目。 I need to check these items, and based on criteria, I need to generate different markup. 我需要检查这些项目,并根据标准,我需要生成不同的标记。 So for example, I have a function that receives an array of items: 例如,我有一个函数接收一个项目数组:

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;
}

The problem is, I cannot simply do array.push() to add individual markups into an array because react doesn't like it for some reason, and I will just end up with gibberish stuff that gets display. 问题是,我不能简单地使用array.push()将单个标记添加到数组中,因为反应因某种原因不喜欢它,而我最终会得到显示的乱码内容。

Any ideas how could I possibly do this? 任何想法我怎么可能这样做?

Your solution should look like this: 您的解决方案应如下所示:

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 is not HTML and you cannot assemble the html elements in multiple steps. JSX不是HTML,你不能在多个步骤中组装html元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM