在 ReactJs 中显示产品数组

Display array of product in ReactJs

我正在实现一个名为 Table 的组件,它是从 react-bootstrap 导入的。我目前正在通过数组将数据从父级传递给子级,但是我很难通过父级写入数组class,我不知道在这种情况下如何编写代码

这是我在 index.js 文件夹 src/components/table/index

中的代码
import React from 'react';
import {Table, Image} from 'react-bootstrap';
import '../Table/index.css';
import Button from '../Button/index';

const TableItem = ({productList}) => {
  const redirectToEdit = () => {
    console.log("Open edit form for me, please?")
  }

  const deleteProductItem = () => {
    console.log("The product has been deleted")
  }
  return(
    <Table striped bordered hover>
      <thead>
        <tr>
          <th>No. </th>
          <th>Image</th>
          <th>Name</th>
          <th>Category</th>
          <th>Price</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
        {productList.map((product, index) => (
          <tr key={index}>
            <td>{product.id}</td>
            <td><Image src={product.image} /></td>
            <td>{product.name}</td>
            <td>{product.category}</td>
            <td>{product.price}</td>
            <td>
              <Button variant="success" onClick={redirectToEdit}>Edit</Button>
              <Button variant="danger" onClick={deleteProductItem}>Delete</Button>
            </td>
          </tr>
        ))}
      </tbody>
    </Table>
  );
}

export default TableItem;

这是我在 app.js 文件夹 src/app.js

中的代码
<TableItem 
   productList={["1", "https://place-hold.it/100x150", "Black milk tea", "Milk Tea", "10000"]}
/>

在上面,我只是添加了1个产品,但是我运行的时候不显示,我的问题是我怎么能写很多products for this in app.js by array

谁能帮帮我,非常感谢?

您必须更改代码中的两件事。首先是传递给您的字典 TableItem 所以代码必须是

const TableItem = (dict) => { 
    productList = dict.productList;
    // then your remaining code..

渲染时需要按如下方式传递 productList:

<TableItem productList={[{id:"1", image:"https://place-hold.it/100x150", name:"Black milk tea",category: "Milk Tea",price: "10000"}]} />

现在让我帮你理清你的概念,第一件事是如果你使用点访问一些属性你必须有一个字典而不是你只有一个列表作为你的产品列表,其次每次在反应中你声明Component u 中的函数或构造函数 class 通过字典传递,通常人们将其命名为 props.

您应该提供一组对象。试试这个

<TableItem     
productList={[
{"id":"1","image": "https://place-hold.it/100x150","name": "Black milk tea","category": "Milk Tea","price": "10000"}
]} />

您可以提供多个项目,例如,

<TableItem     
productList={[
{"id":"1","image": "https://place-hold.it/100x150","name": "Black milk tea","category": "Milk Tea","price": "10000"},
{"id":"2","image": "https://place-hold.it/150x150","name": "Black milk tea 2","category": "Milk Tea 2","price": "10000"},
{"id":"3","image": "https://place-hold.it/230x150","name": "Black milk tea","category": "Milk Tea 3","price": "10000"}
]} />

产品列表数组应如下所示:

const productList=[
{
  id:"1",
  image:"https://place-hold.it/100x150",
  name:"Black milk tea",
  category:"Milk Tea",
  price:"10000"
},{
  id:"2",
  image:"https://place-hold.it/100x150",
  name:"Black milk tea",
  category:"Milk Tea",
  price:"10000"
}];
.
.
.
<TableItem productList={productList} />