【问题标题】:Customizing colors for PrimeReact datatable为 PrimeReact 数据表自定义颜色
【发布时间】:2021-05-17 20:05:34
【问题描述】:

有一种方法可以将背景或文本颜色更改为 PrimeReact 数据表中使用 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

谢谢!

【问题讨论】:

    标签: datatable primereact


    【解决方案1】:

    我已经解决了……

    我所做的是创建一个动态的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" 的字段,那么它将使用此颜色创建样式并将其用作文本颜色。同样可以应用于背景或其他任何东西

    【讨论】:

      猜你喜欢
      • 2021-09-07
      • 2020-01-31
      • 1970-01-01
      • 2018-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-08
      • 1970-01-01
      相关资源
      最近更新 更多