微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为 PrimeReact 数据表自定义颜色

如何解决为 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" 的字段,那么它将使用此颜色创建样式并将其用作文本颜色。同样可以应用于背景或任何东西

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。