首页 > 解决方案 > 如何将道具传递给具有相同组件的两个表

问题描述

我对 react 中的组件面板有疑问

目前,我需要为OrderProduct 创建一个通用组件。但是两张表的列数不同,一侧多列,一侧少列,另外表名也不同。

我有一段这样的代码

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

const TableItem = ({productList}) => {
  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;

我为产品表创建的代码,但订单表不是因为我不知道如何正确执行。我为该列命名为固定,我知道这是错误的,因为订单表也会从该表中检索组件,所以我不能这样命名

订单表也有以下列:用户名、地址、数量、状态......

如何更改可用于两个表的此组件中的代码 谁能帮我解释一下,非常感谢

标签: reactjsreact-component

解决方案


所以你可以做这样的事情,创建一个表格组件,并将其中的列列表和数据作为道具传递,这样你就可以从父组件控制表格,并且可以根据需要以任何方式使用。

 const TableItem = ({data, columns}) => {
  return(
    <Table striped bordered hover>
      <thead>
        <tr>
           { 
             columns.map((column, index) => {
               <th key={ index }>{ column.name }</th>
             }
           }
        </tr>
      </thead>
      <tbody>
        {data.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>
  );
}

在父组件中,您可以执行类似的操作

const parentComponent = () => {
  return {
    <TableItem columns={ productColumns } data={ productData } />
    <TableItem columns={ orderColumns } data={ orderData }
  }
}

注意代码未经测试,是伪代码


推荐阅读