cjd-parkball
Version:
> 中后台业务组件库,中后台就像公园,进入需要买门票(登录),所以以 Parkball(公园球) 命名,公园内必定捕获!作为一个组件库,提供使用方法文档,方便开发者的调用
100 lines (89 loc) • 2.75 kB
JavaScript
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { Table } from 'antd'
import './index.scss'
export default class DiffTable extends PureComponent {
static Wrapper = props => <div className={props.isDifferent ? 'pk-diff-table-different' : ''}>{props.children}</div>
static defaultProps = {
diffKeys: [],
from: {},
to: {},
}
static propTypes = {
diffKeys: PropTypes.arrayOf(PropTypes.object),
from: PropTypes.object,
to: PropTypes.object,
}
columns = [
{
title: '名称',
dataIndex: 'title',
width: 200,
}, {
title: '更新前',
dataIndex: 'fromVal',
render: (text, { renderFrom, fromVal, toVal }) => {
if (typeof renderFrom === 'function') {
return renderFrom(fromVal, toVal, this.props.from, this.props.to)
}
return text || '--'
},
}, {
title: '更新后',
dataIndex: 'toVal',
render: (text, {
renderFrom, renderTo, fromVal, toVal, isDifferent,
}) => {
if (typeof renderTo === 'function' && typeof renderFrom === 'function') {
const from = renderFrom(fromVal, toVal, this.props.from, this.props.to)
const to = renderTo(fromVal, toVal, this.props.from, this.props.to)
if (this.isDiffAble(from) && this.isDiffAble(to)) {
return to ? <DiffTable.Wrapper isDifferent={from !== to}>{to}</DiffTable.Wrapper> : '--'
}
return to
}
if (isDifferent) {
return <DiffTable.Wrapper isDifferent>{text}</DiffTable.Wrapper>
}
return text || '--'
},
},
]
getValueByNestingKey = (targetKey, fromVal, toVal) => {
const arr = targetKey.split('.')
const { length } = arr
return arr.reduce((ret, cur, curIndex) => {
const isLast = curIndex === length - 1
return {
fromVal: ret.fromVal[cur] || (isLast ? '' : {}),
toVal: ret.toVal[cur] || (isLast ? '' : {}),
}
}, { fromVal, toVal })
}
isDiffAble = variable => ['string', 'number', 'undefined'].includes(typeof variable) || variable === null
transferSourceToTableArr = (diffKeys, from, to) => {
return diffKeys.map((t, i) => {
const { fromVal, toVal } = this.getValueByNestingKey(t.dataIndex, from, to)
return {
key: i,
...t,
fromVal,
toVal,
isDifferent: fromVal !== toVal,
}
})
}
render () {
const {
diffKeys, from, to, ...tableOptions
} = this.props
return (
<Table
{...tableOptions}
columns={this.columns}
dataSource={this.transferSourceToTableArr(diffKeys, from, to)}
pagination={false}
/>
)
}
}