需求:
本篇文章適用于表頭同時添加懸浮和排序,另,只需支持文字懸浮對title封一層方法即可eg:
const TooltipTitle = (text, title) => { // text 展示的thead title 展示的提醒文字
return (
<Fragment>
<span style={{ marginRight: 8 }}>{text}</span>
<Tooltip placement="top" title={title}>
<Icon type="question-circle" theme="outlined" />
</Tooltip>
</Fragment>
);
};
ant design中的table中的thead支持信息提示和遠(yuǎn)程加載排序。
在這里插入圖片描述
困難點
ant design 沒有提供兩者同時存在的api;直接添加sorter,同時對我們的title封裝方法,出現(xiàn)點擊排序,只會觸發(fā)單一的一個排序,這不是我們最終達(dá)成的結(jié)果。那么在不對title做處理的情況下,實現(xiàn)信息提示和排序的方法
解決
const columns = [{
title: '姓名',
dataIndex: 'name',
key: 'name',
sorter: true, // 實現(xiàn)排序Icon出現(xiàn),開始交互排序
filterDropdown: true, // 自定義的列篩選功能,我們占位為信息提示Icon的位置
filterIcon: () => {
return (
<Tooltip placement="top" onVisibleChange={() => onVisibleChange(1)}>
// 在這不寫title的原因是ant design 內(nèi)部有很多title,內(nèi)部結(jié)構(gòu)并沒有對特殊的情況做處理,只接收一個title,
// 并覆蓋不了默認(rèn)是篩選。
<Icon type="question-circle" theme="outlined" />
</Tooltip>
);
},
}, {
title: '年齡',
dataIndex: 'age',
key: 'age',
}, {
title: '住址',
dataIndex: 'address',
key: 'address',
}];
onVisibleChange = (key) => { //Tooltip 顯示隱藏的回調(diào),類似onmouseenter 進入離開事件,用來顯示我們不同的信息提醒
let str = '';
switch (key) {
case 1:
str = '你的姓名';
default:
break;
}
this.setState({
filterTitleKey: str,
});
}
handleTableChange = (pagination, filters, sorter) => {
console.log(pagination, filters, sorter);
}
<Table
dataSource={dataSource}
columns={columns}
onChange={() => this.handleTableChange}
locale={{
filterTitle: filterTitleKey || '默認(rèn)', // 設(shè)一個默認(rèn)是防止控制臺的報錯,移除以后造成filterTitle為空,失??;
}}
/>
樣式需要自己去調(diào)整
簡易解釋
ant design table 中 filterIcon api 相關(guān)的源碼解析 ,一些我們未能解決的問題,我們可以通過研究源代碼去分析或可供我們
使用的api方法。
renderFilterIcon = () => {
const { column, locale, prefixCls, selectedKeys } = this.props;
const filtered = selectedKeys && selectedKeys.length > 0;
let filterIcon = column.filterIcon as any;
if (typeof filterIcon === 'function') {
filterIcon = filterIcon(filtered);
}
const dropdownIconClass = classNames({
[`${prefixCls}-selected`]: filtered,
[`${prefixCls}-open`]: this.getDropdownVisible(),
});
return filterIcon ? ( // 重點在這,官網(wǎng)提供了filterIcon api,并未提供filterTitle,來解決我們現(xiàn)實遇到的問題
React.cloneElement(filterIcon as any, {
title: locale.filterTitle, // 因源碼內(nèi)部有個title,我們實現(xiàn)讓它動態(tài)展示,層疊掉默認(rèn)的title
className: classNames(`${prefixCls}-icon`, dropdownIconClass, filterIcon.props.className),
onClick: stopPropagation,
})
) : (
<Icon
title={locale.filterTitle} // 同理上,供我們使用的api
type="filter"
theme="filled"
className={dropdownIconClass}
onClick={stopPropagation}
/>
);
};
有興趣的同學(xué)可以看一看完整的代碼,看看實現(xiàn)的具體過程,小編不才,只展示部分實現(xiàn)的過程,詳細(xì)的原理小編未給出,敬請諒解...