reactjs - 如何将道具传递给具有相同组件的两个表
问题描述
我对 react 中的组件面板有疑问
目前,我需要为Order和Product 表创建一个通用组件。但是两张表的列数不同,一侧多列,一侧少列,另外表名也不同。
我有一段这样的代码
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;
我为产品表创建的代码,但订单表不是因为我不知道如何正确执行。我为该列命名为固定,我知道这是错误的,因为订单表也会从该表中检索组件,所以我不能这样命名
订单表也有以下列:用户名、地址、数量、状态......
如何更改可用于两个表的此组件中的代码 谁能帮我解释一下,非常感谢
解决方案
所以你可以做这样的事情,创建一个表格组件,并将其中的列列表和数据作为道具传递,这样你就可以从父组件控制表格,并且可以根据需要以任何方式使用。
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 }
}
}
注意代码未经测试,是伪代码
推荐阅读
- java - 创建包含多个实例的实例
- elasticsearch - Elasticsearch 中数组字段的最大大小是多少?
- bash - 循环覆盖文件
- javascript - 使用 IFrame Player API 重新打开模态后,Youtube iframe 不显示
- android - 选择文件资源管理器后未初始化 lateinit 属性
- javascript - 如何修复ajax中的[OBJECT OBJECT]来查看数据
- parse-platform - 多个表之间的复杂搜索在 Parse Server 中不起作用?
- c# - Unity - 替换为空
- vue.js - NUXT 中间件存储状态为空,即使开发工具中的 Vuex 显示数据
- jquery - 如何使用 jquery 循环响应