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
useMemoOptimization: Wrapping the column processing inuseMemoensures we only re-process columns when the originalcolumnsprop 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 itsrenderCellmethod to split the value and render each segment in a<p>tag. - Preserve Original Column Settings: By spreading
...columnbefore adding our custom renderer, we keep all existing column configurations (like header text, alignment, sorting behavior) intact.
内容的提问来源于stack exchange,提问作者Ruben Martins
相关产品推荐
相关产品推荐

