代码如下
const column = [
{
title: '序号',
dataIndex: 'index',
key: 'index',
colSpan: 0,
width: '5%',
align: 'center',
render: (text: string, field: { name: string }, index: number) => index + 1,
}];
return <Table dataSource={dataSource} columns={column} pagination={false} bordered />;
错误提醒
重点:属性“align”的类型不兼容。不能将类型“string”分配给类型“AlignType | undefined”。
修改方案一
{
title: '序号',
align: 'center' as 'center',
}
修改方案二
import React, { PureComponent } from "react";
import { Table } from "antd";
//引入culumns泛型
import { ColumnProps } from 'antd/es/table';
interface Iprops {
name: string;
age: number;
}
interface IState {
count: number | string;
value?:number;
}
// 定义列接口
const columns:ColumnProps<IUserInfo>[]= [
{
title: "名字 Name",
width: 100,
dataIndex: "name",
key: "name",
fixed: "left",
},
{
title: "年龄",
width: 100,
dataIndex: "age",
key: "age",
fixed: "left",
},
{ title: "地址", dataIndex: "address", key: "1" },
{ title: "地址2可以重复", dataIndex: "address", key: "2" },
{
title: "操作",
key: "operation",
fixed: "right",
width: 100,
render: () => <a href="#">action</a>,
},
];
//行数据接口
interface IUserInfo {
key:string;
name:string;
age:number;
address:string
}
const data:IUserInfo[] = [
{
key: "1",
name: "John Brown",
age: 32,
address: "New York Park",
},
{
key: "2",
name: "Jim Green",
age: 40,
address: "London Park",
},
];
这样Table组件在使用columns就不会报错了
参考链接:react.js - typescript react项目中如果正确使用antd组件姿势,举个栗子:Table组件columns类型错误 - 个人文章 - SegmentFault 思否