【问题标题】:How to concatenate JSX elements into an array?如何将 JSX 元素连接成一个数组?
【发布时间】: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 转换成什么,希望它会更有意义。粘贴:&lt;div&gt;&lt;span&gt;foo&lt;/span&gt;&lt;/div&gt; 在这里:babeljs.io/repl/…
  • 你有没有让这个工作?我正在尝试做类似的事情。在解析器中,根据 JSON 对象的内容构建 JSX。

标签: javascript reactjs


【解决方案1】:

您的解决方案应如下所示:

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 元素。

【讨论】:

  • 是的,我的解决方案最后看起来确实像这样,因为在 render() 函数中我确实在 div 之间显示 {buffer}。但我认为我的问题是你所指出的,我希望/想要通过首先将内容推入数组来组装最终输出/html。这显然是不可能的。叹息……
  • 我想我不明白的是,在 render() 中我可以使用任意数量的 HTML 元素来显示,只要它们位于最外层的 div 之间。在这个概念上,为什么我不能简单地将所有这些 HTML 元素放入一个变量或一个数组中,并将其显示在最外层的 div 中?这基本上就是我想要做的。
  • @pentool 你可以。
  • 你会这么好心并发布一个简单的例子吗?在过去的 5 个小时里,我一直在尝试这样做,但无论我如何对其进行切片,它都无法正常工作。
  • 啊,我明白了!所以基本上你必须用 both 开头和结尾的 div 将项目推送到数组中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-27
  • 2017-09-21
  • 1970-01-01
  • 2011-03-31
  • 2012-01-07
  • 1970-01-01
  • 2019-12-05
相关资源
最近更新 更多