【发布时间】:2016-11-07 22:47:32
【问题描述】:
React 世界中令人沮丧的时刻...我需要能够根据某些标准创建标记。例如,我收到一组项目。我需要检查这些项目,并且根据标准,我需要生成不同的标记。例如,我有一个接收项目数组的函数:
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 不喜欢它,我最终会得到显示的乱码。
任何想法我怎么可能做到这一点?
【问题讨论】:
-
“我不能简单地执行 'array.push()' 将单个标记添加到数组中,因为由于某种原因 react 不喜欢它,” 原因相同您不能创建 DOM 元素 的一半。 JSX 不是连接 strings 来构建 HTML,而是创建最终呈现给 DOM 元素的组件。如果你看看 JSX 转换成什么,希望它会更有意义。粘贴:
<div><span>foo</span></div>在这里:babeljs.io/repl/…。 -
你有没有让这个工作?我正在尝试做类似的事情。在解析器中,根据 JSON 对象的内容构建 JSX。
标签: javascript reactjs