在React中使用循环将对象的属性渲染为JSX元素:

huangapple go评论77阅读模式
英文:

Rendering an object's properties as JSX elements in React using a loop

问题

我有一个名为tour的对象,其结构如下:

const tour = {
  date: dateBetweenFormat(13), //返回字符串
  where: "NY",
  info: "group full",
  amount: "750$",
  place: "hotel",
};

我想在React中将此对象的属性呈现为JSX元素,避免重复的代码。期望的输出是将每个属性显示在一个<div>元素内,属性名称作为标签,其值显示在其旁边。

我尝试使用for...in循环和Object.entries()来遍历对象的属性,但遇到了一个错误,指出"对象不能作为React子元素"。

以下是我尝试的代码:

<div className="mb-2">
  {(() => {
    const elements = [];
    for (let key in tour) {
      elements.push(
        <div
          key={key}
          className="flex bg-blue-200 px-4 mt-1 h-9 font-bold items-center text-blue-500 text-opacity-60"
        >
          {key}: {tour[key]}
        </div>
      );
    }
    return elements;
  })()}
</div>

以及:

<div className="mb-2">
  {Object.entries(tour).map(([key, value]) => (
    <div
      key={key}
      className="flex bg-blue-200 px-4 mt-1 h-9 font-bold items-center text-blue-500 text-opacity-60"
    >
      {value}
    </div>
  ))}
</div>

期望的输出是:

<div className="mb-2">
  <div className="flex bg-blue-200 px-4 mt-1 h-9 font-bold items-center text-blue-500 text-opacity-60">
    {tour.date}
  </div>
  <div className="flex bg-blue-200 px-4 mt-1 h-9 font-bold items-center text-blue-500 text-opacity-60">
    {tour.info}
  </div>
  <div className="flex bg-blue-200 px-4 mt-1 h-9 font-bold items-center text-blue-500 text-opacity-60">
    {tour.amount}
  </div>
  <div className="flex bg-blue-200 px-4 mt-1 h-9 font-bold items-center text-blue-500 text-opacity-60">
    {tour.place}
  </div>
</div>

请问有人能指导我如何正确使用循环在React中呈现此对象的属性吗?是否有更好的方法可以实现这个目标?提前感谢您的帮助!

英文:

I have an object called tour with the following structure:

const tour = {
  date: dateBetweenFormat(13),//returns string
  where: &quot;NY&quot;,
  info: &quot;group full&quot;,
  amount: &quot;750$&quot;,
  place: &quot;hotel&quot;,
};

I would like to render the properties of this object as JSX elements in React, avoiding repetitive code. The desired output is to have each property displayed within a <div> element, with the property name as a label and its value shown next to it.

I tried using a for...in loop and Object.entries() to iterate over the object's properties, but I encountered an error stating "Objects are not valid as a React child."

Here's the code I attempted:

&lt;div className=&quot;mb-2&quot;&gt;
  {(() =&gt; {
    const elements = [];
    for (let key in tour) {
      elements.push(
        &lt;div
          key={key}
          className=&quot;flex bg-blue-200 px-4 mt-1 h-9 font-bold items-center text-blue-500 text-opacity-60&quot;
        &gt;
          {key}: {tour[key]}
        &lt;/div&gt;
      );
    }
    return elements;
  })()}
&lt;/div&gt;

And:

&lt;div className=&quot;mb-2&quot;&gt;
          {Object.entries(tour).map(([key, value]) =&gt; (
            &lt;div
              key={key}
              className=&quot;flex bg-blue-200 px-4 mt-1 h-9 font-bold items-center text-blue-500 text-opacity-60&quot;
            &gt;
              {value}
            &lt;/div&gt;
          ))}
        &lt;/div&gt;

Expecting:

&lt;div className=&quot;mb-2&quot;&gt;
          &lt;div className=&quot;flex bg-blue-200  px-4 mt-1 h-9 font-bold items-center text-blue-500 text-opacity-60&quot;&gt;
            {tour.date}
          &lt;/div&gt;
          &lt;div className=&quot;flex bg-blue-200  px-4 mt-1 h-9 font-bold items-center text-blue-500 text-opacity-60&quot;&gt;
            {tour.info}
          &lt;/div&gt;
          &lt;div className=&quot;flex bg-blue-200  px-4 mt-1 h-9 font-bold items-center text-blue-500 text-opacity-60&quot;&gt;
            {tour.amount}
          &lt;/div&gt;
          &lt;div className=&quot;flex bg-blue-200  px-4 mt-1 h-9 font-bold items-center text-blue-500 text-opacity-60&quot;&gt;
            {tour.place}
          &lt;/div&gt;
        &lt;/div&gt;

Can someone please guide me on how to correctly render the properties of this object using a loop in React? Is there a better approach I can take to achieve this?

Thank you in advance for your help!

答案1

得分: 1

你尝试过类似以下的代码吗:

<div className="mb-2">
  {Object.keys(tour).map((key) => {
    return (
      <div
        key={key}
        className="flex bg-blue-200 px-4 mt-1 h-9 font-bold items-center text-blue-500 text-opacity-60"
      >
        {key}: {tour[key]}
      </div>
    );
  })}
</div>
英文:

Did you try something like:

&lt;div className=&quot;mb-2&quot;&gt;
  {Object.keys(tour).map((key) =&gt; {
    return (
       &lt;div
        key={key}
        className=&quot;flex bg-blue-200 px-4 mt-1 h-9 font-bold items-center text-blue-500 text-opacity-60&quot;
      &gt;
        {key}: {tour[key]}
      &lt;/div&gt;
    )
  })}
&lt;/div&gt;

答案2

得分: 0

尝试像这样写:

    <div className="mb-2">
      {Object.keys(tour).map((key) => (
        <div key={key} className="flex bg-blue-200 px-4 mt-1 h-9 font-bold items-center text-blue-500 text-opacity-60">
          {key}: {tour[key]}
        </div>
      ))}
    </div>
英文:

Try it like this :

&lt;div className=&quot;mb-2&quot;&gt;
  {Object.keys(tour).map((key) =&gt; (
    &lt;div key={key} className=&quot;flex bg-blue-200 px-4 mt-1 h-9 font-bold items-center text-blue-500 text-opacity-60&quot;&gt;
      {key}: {tour[key]}
    &lt;/div&gt;
  ))}
&lt;/div&gt;

答案3

得分: 0

I was able to get it working in a code sandbox here: https://codesandbox.io/s/react-repl-forked-nc4hj5?file=/src/index.js

I tried both methods and I removed the date from the object because I didn't have that function provided. I think there's something wrong with your date format function. It's not returning a string likely and it's throwing that error.

Make sure you use .toString() on the date object before returning it.

Can you provide the date format function?

英文:

With your code you provided I was able to get it working in a code sandbox here https://codesandbox.io/s/react-repl-forked-nc4hj5?file=/src/index.js

I tried both methods and I removed the date from the object because I didn't have that function provided. I think there's something wrong with your date format function. It's not returning a string likely and it's throwing that error.

Make sure you use .toString() on the date object before returning it

Can you provide the date format function?

huangapple
  • 本文由 发表于 2023年6月8日 22:09:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76432733.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定