自定义PrimeReact数据表的颜色



有一种方法可以在PrimeReact Datatable中使用rowClassName={rowClass}更改背景或文本颜色,其中rowClass是允许返回CSS文件中配置的类的函数。

但是…如果我想选择任意的颜色呢?例如,一个从数据库中获取#RRGGBB格式?

阅读文档,我看不到调用函数返回样式字符串的方法。另一种方法是动态创建类名,例如…

class RRGGBB为选定的颜色,定义这个类的背景:#RRGGBB和让rowClassName={rowClass}调用rowClass函数返回这个动态创建的类…

我有这种方法,但不工作:

const mycolor = "#00ff00";
function createStyle() {
const style = document.createElement("style");
// add CSS styles
style.innerHTML = `
.lulu {
color: white;
background-color: ${mycolor};
}
`;
// append the style to the DOM in <head> section
document.head.appendChild(style);
}
createStyle();
const rowClass = (data) => {
return {
"lulu": data.category === "Accessories"
};
};
.....
<DataTable value={products} rowClassName={rowClass}>

这段代码是一个修改版本的样例代码由prime react,这里,在沙盒:https://codesandbox.io/s/o6k1n

谢谢!

我已经解决了…

我所做的是创建一个动态css,然后使用它:

function createStyle(color) {
var style = document.getElementsByTagName("style");
var colortag = color.replace("#", "mycolor");
//Assuming there is a style section in the head
var pos = style[0].innerHTML.indexOf(colortag);    
if(pos<0)
style[1].innerHTML += "."+colortag+`
{
color: ${color}!important;
}
`;
return colortag;
const rowClass = (data) => {
var colortag;
if (data.COLOR!=undefined)
colortag=createStyle(data.COLOR);
return { [colortag]: ata.COLOR!=undefined };
}
<DataTable  ref={dt} value={Data} rowClassName={rowClass}>
<column>......</column>
</DataTable>

在这段代码中,如果数据中有一个名为COLOR的字段:"#RRGGBB"然后它将创建一个这种颜色的样式,并使用它作为文本颜色。同样可以应用于背景或其他

最新更新