首页 > 解决方案 > 如何将未关闭的 div 推送到我的数组中?

问题描述

想知道为什么这个会引发错误:

arraysOfUserResults.push(<div>)
arraysOfUserResults.push("line of text")
arraysOfUserResults.push(</div>)

我在返回方法之前写了这个。

基本上我想要做的是这样的循环:(伪代码

Start of object's keys iterating Loop
push opening of div with class name to the array
   Start of object values iterating loop
   push these values to the array
push closing of div to array

然后,将此数组放在大括号内的返回方法上。

谢谢你。

标签: javascriptreactjs

解决方案


在 JSX 中<div>line of text</div>只是. 所以写React.createElement('div', null, 'line of text')

arraysOfUserResults.push(
  <div>
)
arraysOfUserResults.push(
  "line of text"
)
arraysOfUserResults.push(
  </div>
)

类似于写作

arraysOfUserResults.push(
  React.createElement('div', null,
)
arraysOfUserResults.push(
  "line of text"
)
arraysOfUserResults.push(
  )
)

这没有任何意义。开始和结束标签仅界定元素的边界。当您的代码运行时,它们不存在。

如果"line of text"真的应该是一个对象的值数组,并且这些值是原语,则可以将它们作为 JavaScript 表达式包含在 JSX 中:

<div>{Object.values(myObject)}</div>

每个值都将成为<div>.


推荐阅读