在 React 中为 JSON 对象数组创建无状态组件

发布日期:2026-07-03 21:03:04   来源 : 杭州电子商务研究院    浏览量 :9
杭州电子商务研究院 发布日期:2026-07-03 21:03:04  
9

介绍

在 React.js 中将数组绑定到一组 DOM 元素 (JSX) 是应用开发中的常见任务。通常,您需要列出一组对象及其相应的属性,例如产品目录、会员记录或交易列表中的属性。在本指南中,我们将介绍在 React.js 组件的界面中绑定对象列表时的一些注意事项。

设置

假设您正在创建一个 React.js 组件,该组件列出了客户可以在杂货店购买的一组产品。每种产品都有一个idnameprice。数据可能来自任何地方,例如 API 或其他组件。无论如何,您可以预期项目数组将如下所示:

      
  { id: 1
    

这种类型的数据将作为组件中称为items的props属性传递。

首先,创建一个如下所示的组件:

      import React from 'react';

export default class ItemsList extends React.Component {
  constructor(props) {
    super(props);

    this.state = {}
  }

  render() {
    return (
      <table>
        <thead>
          <th>
            Item
          </th>
          <th>
            Price
          </th>
        </thead>
        <tbody>
        </tbody>
      </table>
    );
  }
}
    

请注意,您没有任何状态需要维护,并且此组件以<table>的形式返回单个元素。所有内容都将从props而不是state中读取。在<table>中,React.js 要求您在插入行之前包含<tbody>。否则,它会抱怨<tr>不是<table>的有效子元素。

填充表格

不要将项目数组直接渲染到render(),而是创建一个单独的函数来处理 DOM 元素的构建:

      renderRows() {
  return  this.props.items.map(function(o) {
            return  <tr key={"item-" + o.id}>
                      <td>{o.name}</td>
                      <td>{o.price}</td>
                    </tr>
          });
}
    

Notice first that the code references this.props and assumes that it will have an attribute items. Since it's calling from this.props, it expects that this data will be passed from an external component. Second, the code uses the map function of a JavaScript array to iterate through this.props.items, which accepts a function that returns a <tr> element. Finally, the <tr> element will contain a key attribute. This is a requirement for React.js wherein each child element of a parent element that is dynamically generated has to be assigned a key unique within the parent element. Since it is assumed that each item will contain an id unique to it, the code uses that information to generate the key value of item-someItemId.

Invoke the function within the component's render() inside the <tbody> tag:

      <tbody>
  {this.renderRows()}
</tbody>
    

These items will change if a component calling ItemsList passes a new set of values for items via props.

Overall Code

      import React from 'react';

export default class ItemsList extends React.Component {
  constructor(props) {
    super(props);

    this.state = {}
  }

  renderRows() {
    return  this.props.items.map(function(o) {
              return  <tr key={"item-" + o.id}>
                        <td>{o.name}</td>
                        <td>{o.price}</td>
                      </tr>
            });
  }

  render() {
    return (
      <table>
        <thead>
          <th>
            Item
          </th>
          <th>
            Price
          </th>
        </thead>
        <tbody>
          {this.renderRows()}
        </tbody>
      </table>
    );
  }
}
    

Loading Values

Suppose that you want to test it out. From an external JavaScript section in your app, invoke ItemsList with some data in a DOM element react-root-div:

      var items = [
  { id: 1, name: "Apple", price: 25.00 },
  { id: 2, name: "Oranges", price: 20.00 },
  { id: 3, name: "Grapes", price: 22.00 }
];

ReactDOM.render(
  <ItemsList items={items} />,
  document.getElementById("react-root-div")
);
    

You should see the table render with the name of the item in the first column and its price in the second column. To add more rows to the table, add more objects to items, making sure that each object has an id different from the existing objects in the array.

Conclusion

In this guide, you've created a component that has no state but populates a list of JavaScript objects often derived from a JSON object. The component renders these items dynamically, and each child element rendered should have a unique key within its parent element. Because it is a stateless component, you can easily plug this component in other parts of your React.js app that need a list rendered of items.

For an extra challenge, see if you can integrate this in your own React.js app where data is coming from an external API instead of being hardcoded.

以上内容来自杭州电子商务研究院推送
关注
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据