参考链接:https://material-table.com/#/docs/features/editable
-
安装
安装包
npm install material-table @material-ui/core --save
yarn add material-table @material-ui/core
安装图标
npm install @material-ui/icons --save OR
yarn add @material-ui/icons -
创建文件tableIcon.tsx保存表格图标设置
-
表格组件(table.tsx)
import {MachineService} from '../../services/CalcService'
import MaterialTable from "material-table";
import {tableIcons} from './tableIcon'
// 引入列配置
import {columns} from './columns'
export default class MTable extends Component<any,any>{
service = new MachineService();
constructor(props:any) {
super(props)
this.state = {
data: [],
columns,
isLoading: true,
}
}
onRowAdd = async (newData:any) => {
this.startLoading()
let resp = await this.service.createData(newData)
this.stopLoading()
}
onRowUpdate = async (newData:any,oldData:any) => {
this.startLoading()
newData.chip_tech = +newData.chip_tech
if (+newData.price !== +oldData.price) {
newData.price_at = new Date()
}
let resp = await this.service.updateData(newData)
await this.getData()
this.stopLoading()
}
onRowDelete = async (oldData:any) => {
this.startLoading()
let resp = await this.service.deleteData(oldData)
await this.getData()
this.stopLoading()
}
getData = async () => {
//获取表格接口数据
}
async componentDidMount(){await this.getData()}
render(){
return (
<div style={{ maxWidth: "100%" }}>
<MaterialTable
isLoading={this.state.isLoading}
icons={tableIcons}
key="machine_table"
columns={this.state.columns}
data={this.state.data}
title="矿机列表"
options={
{
paging: false, // 是否显示分页插件
exportButton: true, //是否显示导出按钮
actionsColumnIndex: -1, // actions显示在最后一列
addRowPosition: "first", // 点击添加行时显示在首行
}
}
editable={{
onRowAdd: this.onRowAdd,
onRowUpdate: this.onRowUpdate,
onRowDelete:this.onRowDelete,
}}
/>
</div>
)
}
- 列配置文件(columns.tsx)
export const columns =[
title: "价格",
field: "price",
dataIndex: ["price"],
editComponent: (props: any) => {
let price_source = props?.rowData?.price || "other";
return (
<Select
value={price}
id="price_source"
onChange={(e) => props.onChange(e.target.value)}
>
{Object.entries(MACHINE_PRICE_SOURCE).map(([price, name], idx) => {
return <MenuItem value={price
}>{name}</MenuItem>;
})}
</Select>
);
},
render: (rowData: any) => {
let price_source = rowData?.price_source;
if (price_source) {
return MACHINE_PRICE_SOURCE[price_source];
} else {
return MACHINE_PRICE_SOURCE.other;
}
}
]