📌  相关文章
📜  功能组件如何添加到现有数组反应 - Javascript(1)

📅  最后修改于: 2023-12-03 15:36:58.398000             🧑  作者: Mango

在现有 React 数组中添加功能组件的方法

当我们开发一个 React 应用时,经常需要在数组中添加功能组件,以显示列表中的每个项目。这篇文章将介绍如何在现有的 React 数组中添加一个功能组件,并向您展示如何正确传递属性。

创建一个基本的功能组件

首先,让我们创建一个基本的功能组件。我们将称其为“ListItemView”,其任务是渲染我们的列表项。下面是我们的示例代码:

import React from "react";

const ListItemView = (props) => {
  return (
    <div className="list-item">
      <h3>{props.title}</h3>
      <p>{props.description}</p>
    </div>
  );
};

export default ListItemView;
创建包含数组数据的父组件

接下来,我们需要创建一个父组件,它将在其状态中存储我们的数组数据。我们将称其为“ListView”。在我们的例子中,我们使用“ListView”来存储一些图书数据。下面是我们的示例代码:

import React, { Component } from "react";
import ListItemView from "./ListItemView";

class ListView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      books: [
        {
          title: "The Lean Startup",
          description: "Master the Art of Business",
        },
        {
          title: "Think and Grow Rich",
          description: "The Original Version, Restored and Revised",
        },
        {
          title: "The Alchemist",
          description: "A Fable About Following Your Dream",
        },
      ],
    };
  }

  render() {
    return (
      <div className="list-view">
        {this.state.books.map((book, index) => (
          <ListItemView
            key={index}
            title={book.title}
            description={book.description}
          />
        ))}
      </div>
    );
  }
}

export default ListView;

在“ListView”组件的状态中,我们定义了一个包含三个图书对象的数组。然后,我们在“render”方法中对该数组进行映射,并使用“ListItemView”将其渲染到我们的列表中。

在现有数组中添加功能组件

假设我们需要添加一个新书籍到列表中。我们可以使用以下代码来修改“ListView”组件的状态:

this.setState({
  books: [
    ...this.state.books,
    {
      title: "The 7 Habits of Highly Effective People",
      description: "Powerful Lessons in Personal Change",
    },
  ],
});

我们使用ES6的展开运算符扩展原始数组,然后添加一个新的包含书名和描述的对象。这样,我们就可以在现有数组中添加一个新的功能组件。

传递属性给功能组件

在我们的示例代码中,我们需要传递每本书的标题和描述给“ListItemView”组件。我们可以使用以下代码片段来实现:

<ListItemView
  key={index}
  title={book.title}
  description={book.description}
/>

我们将“key”属性设置为“index”,这是在映射过程中使用的数组中当前项的索引。我们在所有其他属性中传递图书对象的“title”和“description”属性。这些属性将在“ListItemView”组件中作为“props”参数传递,以便我们在渲染期间访问它们。

结论

在现有 React 数组中添加功能组件是一项非常简单的任务。您只需要在父组件中映射数组,在映射过程中传递必要的属性,并使用展开运算符来添加新的对象。这些技术将帮助您构建可维护和可伸缩的 React 应用程序,并帮助您轻松管理列表和其他重复的 UI 元素。