
import React, {memo} from 'react';import PropTypes from 'prop-types';import { Table } from 'antd';const children = [{title: '总分',dataIndex: 'total',key: 'total',width: 100,},{title: '语文',dataIndex: 'chinese',key: 'chinese',width: 100,},{title: '数学',dataIndex: 'math',key: 'math',width: 100,},{title: '英语',dataIndex: 'en',key: 'en',width: 120,},{title: '化学',dataIndex: 'chemistry',key: 'chemistry',width: 90,},];const columns = [{title: '姓名',dataIndex: 'name',key: 'name',width: 100,},{title: '1月',children,},{title: '2月',children,},{title: '3月',children,},{title: '4月',children,},{title: '5月',children,},];columns.forEach((item, index) => {if(item.children) {item.children = item.children.map(child => {return {...child, key: `${child.key}-${index}-${item.title}` }})}});TableSercieIndex.propTypes = {value: PropTypes.object.isRequired,onChange: PropTypes.func.isRequired,};function TableSercieIndex({value, onChange}) {const { loading, dataSource } = value;const attrs = {rowKey: 'id',size: 'middle',scroll: {x: 2000},loading,columns,dataSource,onChange,bordered: true,}return (<Table {...attrs}/>);}function propsEqual(prevProps, props) {const { dataSource } = prevProps.valuereturn dataSource === props.value.dataSource}export default memo(TableSercieIndex, propsEqual);
自定义render
import { Icon } from 'antd';function Status({ value = '' }) {const include = String(value).includes('-');const upDown = include ? 'arrow-down' : 'arrow-up';const style = { color: include ? '#ff4d4f' : '#52c41a' };return (<>{value} <Icon type={upDown} style={style} /></>);}const columns = [{title: '姓名',dataIndex: 'name',key: 'name',},{title: 'VIP',dataIndex: 'vip',key: 'vip',render: text => <Status value={text} />,},];
优化点
- memo
- 父级的 onChange 用 useCallback包裹一下
key报错
columns & children,数据项中的 key不能一样,否则报错
- 提交一个空数据时,react循环,也可能会出现错误警告
- 或者,只要去掉重复的选项的key,就不会报错
Encountered two children with the same key,{title: '姓名',dataIndex: 'name',key: 'name', // key必须是唯一的,不能有一样的width: 90,},
name. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version
require-default-props
ESLint: propType”onChange”isnotrequired, buthasnocorrespondingdefaultPropsdeclaration.(react/require-default-props)
TableList.propTypes = {value: PropTypes.object,onChange: PropTypes.func.isRequired,};// 增加 .defalutProps解决 eslint报错TableList.defaultProps = {value: {},}function TableList({value, onChange}) {}
