我正在學習使用道具并重構 Reactjs 中的代碼。在表格上作業以列印資料時,我每次都重復表格標題。
Table.js
import React from "react";
const Table = ({ Service, Time, Price }) => {
return (
<div>
<table>
<tr>
<th>Service</th>
<th>Time</th>
<th>Price</th>
<th>Action</th>
</tr>
<tr>
<td> {Service}</td>
<td>{Time}</td>
<td>{Price}</td>
</tr>
</table>
</div>
);
};
export default Table;
以及我嘗試使用道具的服務類。
import React from "react";
import Table from "../../Components/Table";
const Services = () => {
return (
<div>
<Table Service={"Toes"} Time={"15 min"} Price={"$12"} />
<Table Service={"Ears"} Time={"15 min"} Price={"$15"} />
<Table Service={"Nose"} Time={"15 min"} Price={"$15"} />
</div>
);
};
匯出默認服務;但它顯示
Service Time Price Action
Toes 15 min $12
Service Time Price Action
Ears 15 min $15
Service Time Price Action
Nose 15 min $15
誰能幫我在這種情況下如何使用回圈?
uj5u.com熱心網友回復:
你可以試試:
import React, { useState } from "react";
const Table = ({ array }) => {
const [services, setServices] = useState(array);
return (
<div>
<table>
<tr>
<th>Service</th>
<th>Time</th>
<th>Price</th>
<th>Action</th>
</tr>
{services.map(({ Service, Time, Price }) => (
<tr>
<td> {Service}</td>
<td>{Time}</td>
<td>{Price}</td>
</tr>
))}
</table>
</div>
);
};
export default Table;
您的服務可能如下所示:
import React from "react";
const defaultState = [
{ Service: "Toes", Time: "15 min", Price: 12 },
{ Service: "Ears", Time: "15 min", Price: 15 },
{ Service: "Nose", Time: "15 min", Price: 15 },
];
const Services = () => {
return (
<div>
<Table array={defaultState} />
</div>
);
};
export default Services;
您可以將資料作為服務中的陣列。
uj5u.com熱心網友回復:
您只需要一個表組件,然后通過將資料從處于狀態的物件映射到 JSX 組件來創建每一行。
const defaultState = [
{ service: "Toes", time: "15 min", price: 12 },
{ service: "Ears", time: "15 min", price: 15 },
{ service: "Nose", time: "15 min", price: 15 }
];
const Table = () => {
const [services, setServices] = useState(defaultState);
return (
<div>
<table>
<tr>
<th>Service</th>
<th>Time</th>
<th>Price</th>
<th>Action</th>
</tr>
{services.map(service => (
<Service data={service} />
))}
</table>
</div>
);
}
const Service = ({ service, time, price }) => {
return (
<tr>
<td>{service}</td>
<td>{time}</td>
<td>${price}</td>
</tr>
);
}
然后,當您最終希望從 API 或用戶更新行時,您可以分別使用useEffect鉤子或<input />元素來修改狀態。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/442914.html
上一篇:用于計算基本拉格朗日多項式的Python代碼對于大量資料而言花費的時間太長
下一篇:在C中列印帕斯卡三角形
