问题描述
使用Handsontable的React包装器。数据将子行嵌套了几层。
数据如下:
[
{
category: "Category A",subCategory: null,subItem: null,value: "abc 123",__children: [
{
category: null,subCategory: "Sub Category 1",value: "xyz 456",},{
category: null,subCategory: "Sub Category 2",value: "qwe 987",__children: [
{
category: null,subItem: "Sub Item I",value: "asd 987",],{
category: "Category B",value: "abc 345",__children: null,]
假设我需要“类别A”下的所有内容均为绿色,但不需要“类别B”下的所有内容。该怎么办?
我尝试传递一个cells
函数(row,col,prop) => {...}
,但这仅给了我行和列的索引。行索引根据折叠的类别而变化。因此,我需要能够根据父行的category
的值来对整个行进行样式设置。
解决方法
由于几乎所有配置都基于行索引和col索引,因此很难实现此功能,我发现的唯一解决方法是沿值添加颜色并使用自定义渲染器评估字符串中是否有元数据,您需要预先准备数据
const data = [
{
category: "Category A",subCategory: null,subItem: null,value: "abc 123#color:green",__children: [
{
category: "#color:green",subCategory: "Sub Category 1#color:green",value: "xyz 456"
},{
category: null,subCategory: "Sub Category 2",value: "qwe 987",__children: [
{
category: null,subItem: "Sub Item I#color:green",value: "asd 987"
}
]
}
]
},{
category: "Category B",value: "abc 345",__children: null
}
];
...
const renderer = (instance,TD,row,col,prop,value,cellProperties) => {
TD.innerHTML = "";
if (value) {
if (value.indexOf("#color:") >= 0) {
const [realValue,color] = value.split("#color:");
TD.style.backgroundColor = color;
TD.innerHTML = realValue;
} else {
TD.innerHTML = value;
}
}
return TD;
};
...
<HotTable
data={data}
colHeaders={true}
rowHeaders={true}
nestedRows={true}
observeChanges
renderer={renderer}
licenseKey="non-commercial-and-evaluation"
/>
您可以在这里https://codesandbox.io/s/handsontable-epbpi?file=/src/index.tsx看到它的工作