You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何访问MUI X DataGrid组件的TableCell并对指定列单元格应用自定义函数

Solution for Custom Rendering in Curso Column

Hey there! Let's get your Curso column rendering split values into <p> tags within your wrapped DataTable component. Here's a clean, maintainable approach:

Step-by-Step Explanation

The key idea is to modify the columns prop inside your DataTable to add a custom renderer specifically for the Curso column. We'll use React's useMemo to avoid unnecessary re-renders when columns or rows change, keeping your component performant.

Modified DataTable Code

import * as React from 'react';
import { DataGrid } from '@mui/x-data-grid';
import { PropTypes } from 'prop-types';

export default function DataTable({ rows, columns, func }) {
  // Process columns to add custom rendering for the Curso column
  const processedColumns = React.useMemo(() => {
    return columns.map(column => {
      // Check if this is the Curso column (match your actual field name)
      if (column.field === 'curso') {
        return {
          ...column,
          // Add custom cell renderer logic
          renderCell: (params) => {
            const cursoValue = params.row.curso;
            if (!cursoValue) return null;
            
            return (
              <div>
                {cursoValue.split('/').map((curs, idx) => (
                  <p key={idx}>{curs}</p>
                ))}
              </div>
            );
          }
        };
      }
      // Return all other columns with their original configuration
      return column;
    });
  }, [columns]); // Re-run only when the original columns prop changes

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid
        rows={rows}
        columns={processedColumns} // Use the processed columns instead of the original
        pageSize={5}
        rowsPerPageOptions={[5]}
        onCellClick={func}
      />
    </div>
  );
}

DataTable.defaultProps = {
  func: () => {},
};

DataTable.propTypes = {
  rows: PropTypes.arrayOf(
    PropTypes.shape({
      conteudo: PropTypes.string,
      disciplina: PropTypes.string,
      curso: PropTypes.string,
      data: PropTypes.string,
    })
  ).isRequired,
  // eslint-disable-next-line react/forbid-prop-types
  columns: PropTypes.array.isRequired,
  func: PropTypes.func,
};

Key Details

  • useMemo Optimization: Wrapping the column processing in useMemo ensures we only re-process columns when the original columns prop changes, preventing unnecessary work on every render.
  • Targeted Renderer: We check for the column with field: 'curso' (adjust this if your column uses a different field name, like 'Curso' with a capital C), then override its renderCell method to split the value and render each segment in a <p> tag.
  • Preserve Original Column Settings: By spreading ...column before adding our custom renderer, we keep all existing column configurations (like header text, alignment, sorting behavior) intact.

内容的提问来源于stack exchange,提问作者Ruben Martins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 23:09:08