首页 > 解决方案 > 如何在 React mui-Datatable 中完成 customRender

问题描述

我想自定义 mui-datatble 中的行帽数据,如果我在选项中选择是,背景颜色应该是红色,如果我说否,背景颜色应该是蓝色。我第一次使用mui-datatable。

我无法使用 customRowRender 或 customRender。我们如何在 mui-datatable 中使用它

import React from 'react';
import MUIDataTable from "mui-datatables";

class Datatable extends React.Component {
    render() {
        const columns = [
            {
             name: "name",
             label: "Name",
             options: {
              filter: true,
              sort: true,
              customRowRender:(data, dataIndex, rowIndex) => {
                console.log('data' + data);
                return (
                  <div>
                    {data}{' '}{dataIndex}{' '}{rowIndex}
                  </div>
                );
              }
             }
            },
            {
             name: "company",
             label: "Company",
             options: {
              filter: true,
              sort: false,
             }
            }
           ];

           const data = [
            { name: "Joe James", company: "Test Corp" },
            { name: "John Walsh", company: "Test Corp" }
           ];

           const options = {
             filterType: 'checkbox',
           };
        return (
            <React.Fragment>
<MUIDataTable
  title={"Employee List"}
  data={data}
  columns={columns}
  options={options}
/>
            </React.Fragment>
            );
   }}
export default Datatable;

I should be able to render data in customRender where I will add a conditional render with a <div> and style depending on Yes/No

标签: reactjsdatatablemui-datatable

解决方案


您已将customRowRender属性放入columns对象中,根据文档,它应该在options对象中:

   const options = {
             filterType: 'checkbox',
             customRowRender:(data, dataIndex, rowIndex) => {
                console.log('data' + data);
                return (
                  <div>
                    {data}{' '}{dataIndex}{' '}{rowIndex}
                  </div>
                );
              }
    };

    // render
    <MUIDataTable
      title={"Employee List"}
      data={data}
      columns={columns}
      options={options}
    />

但这是用于渲染自定义行,如果要渲染自定义列,则可以customBodyRendercolumns对象中使用属性。


推荐阅读