简介:Handsontable是用于Web应用程序的类似Excel的JavaScript数据网格组件,本文主要介绍它的自定义渲染,其他API请至 官方文档 查阅。
起因:项目结构复杂,在单元格内有各种的操作交互,如:排序,筛选后显示小图标,字体的加粗,字体大小等,所以就需要一个二维的数组对象来表达数据结构了。但是这时候在编辑的时候就出现了一个问题,单元格显示出了[object object]。下面是几种解决此问题的方式。
1.修改 editor
const ResetEditor = Handsontable.editors.TextEditor.prototype.extend();ResetEditor.prototype.prepare = function(row, col, prop, td, originalValue, cellProperties) { Handsontable.editors.BaseEditor.prototype.prepare.call( this, row, col, prop, td, originalValue ? originalValue.myValue: '', //这里originalValue是单元格数据对象,myValue为要显示的值 cellProperties );};ResetEditor.prototype.saveValue = function(value, ctrlDown) { let physicalRow = this.instance.runHooks('modifyRow', this.row); let valueToSet = value[0][0]; //设值 this.originalValue = valueToSet; this.instance.setDataAtRowProp(physicalRow, this.prop, valueToSet, 'edit');};
columns: function(index) { //给每一个单元格都加上自定义Editor,可以定义多个Editor return { editor: ResetEditor };}
缺点:不能新增列了,如果是一个固定行列数的表格可以使用
2.官方例子
class CustomEditor extends Handsontable.editors.TextEditor { constructor(props) { super(props); } createElements() { super.createElements(); this.TEXTAREA = document.createElement('input'); this.TEXTAREA.setAttribute('placeholder', 'Custom placeholder'); this.TEXTAREA.className = 'handsontableInput'; this.textareaStyle = this.TEXTAREA.style; Handsontable.dom.empty(this.TEXTAREA_PARENT); this.TEXTAREA_PARENT.appendChild(this.TEXTAREA); }}
备注:这个没有能实现,应该需要付费版本才可以吧
3.修改源码
在源码 src/editors/_baseEditor.js line 118
中(^"6.2.2"),如果不是字符串,它就stringify了一下,所以我们可以修改一下这个判断,来正常显示我们的数据。
4.整理数据结构
export default function(cellsDataMap) {
//通过坐标来显示的数据
return function(instance, td, row, col, prop, value, cellProperties) { let display = value || ''; const dataKey = `${row},${col}`; //获取当前单元格坐标 const cellValue = cellsDataMap && cellsDataMap[dataKey]; //从cellsDataMap取值 if (cellValue) { const columnObj = cellValue.cell_format && cellValue.cell_format.m_field; if (columnObj) {
//在此可以通过数据给td添加各种交互,下面仅为显示内容 //cellProperties.readOnly = true; //设置可编辑性
display = columnObj.display; } } td.innerHTML = display; return td; };}
renderer: customRenderer(cellsDataMap) //上面的自定义渲染方法注册进renderer
备注:推荐使用,只需整理好数据结构就可以,不会带来其他影响