如何将JSX元素串联到数组中? [英] How to concatenate JSX elements into an array?
问题描述
React世界中令人沮丧的时间...我需要能够根据某些条件创建标记.例如,我收到一系列物品.我需要检查这些项目,并且根据条件,我需要生成不同的标记.例如,我有一个接收项目数组的函数:
Frustrating times in React world... I need to be able to create markup based on certain criterias. 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;
}
问题是,我不能简单地执行 array.push()
将单个标记添加到数组中,因为由于某些原因react不喜欢它,所以我只会得到乱码会显示出来.
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.
任何想法我怎么可能做到这一点?
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不是HTML,因此无法分多个步骤组装html元素.
JSX is not HTML and you cannot assemble the html elements in multiple steps.
这篇关于如何将JSX元素串联到数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!