如何在ReactJS的DataGrid中为指定列添加图标
React DataGrid Role列添加自定义图标实现方案
需求说明
需要在ReactJS的DataGrid组件的Role列中,根据角色类型(Sender/Receiver)添加对应图标,实现图标+文字的显示效果。
当前表格样式

期望表格样式

当前代码
function DataGridExample() { const [platform, setPlatform] = useState([]); const [searchText, setSearchText] = useState(''); const [rows, setRows] = useState([]); useEffect(() => { let platformList = [ { id: 1, role: 'Sender', counter_party: "Bharath", token: "1.000", date:"16-03-2022 06:20 AM", comments:'Test First Transfer' }, { id: 2, role: "Sender", counter_party: "Harish", token: "1.000" , date:"14-03-2022 08:59 AM", comments:'Testing from hosted'}, { id: 3, role: "Receiver", counter_party: "Vijay", token: "1.000", date:"14-03-2022 08:53 AM", comments:'Test First Transfer'}, ]; setPlatform(platformList); setRows(platformList); }, []); const columns = [ { field: 'role', headerName: 'Role', width: 150,}, { field: 'counter_party', headerName: 'Counter Party', width: 200 }, { field: 'token', headerName: 'Token', width: 150 }, { field: 'date', headerName: 'Date', width: 200 }, { field: 'comments', headerName: 'Comments', width: 200 } ]; function escapeRegExp(value) { return value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); } const requestSearch = (searchValue) => { const searchRegex = new RegExp(escapeRegExp(searchValue), 'i'); const filteredRows = platform.filter((row) => { return Object.keys(row).some((field) => { return searchRegex.test(row[field].toString()); }); }); setRows(filteredRows); }; return ( <div> <div style={{ height: 400, width: '100%' }}> <Box> <TextField variant="outlined" size='small' value={searchText} onChange={(e) => { setSearchText(e.target.value); requestSearch(e.target.value) }} placeholder="Search..." InputProps={{ startAdornment: <SearchIcon fontSize="small" color="action" />, endAdornment: ( <IconButton title="Clear" aria-label="Clear" size="small" style={{ visibility: searchText ? 'visible' : 'hidden', borderRadius: "57%", paddingRight: "1px", margin: "0", fontSize: "1.25rem" }} onClick={(e) => { setSearchText(''); setRows(platform) }} > <ClearIcon fontSize="small" color="action" /> </IconButton> ), }} /> </Box> <DataGrid disableColumnMenu rows={rows} columns={columns} pageSize={10} rowsPerPageOptions={[10]} /> </div> </div > ); } export { DataGridExample };
实现方案
核心思路
利用DataGrid提供的renderCell属性自定义Role列的渲染逻辑,根据单元格的角色值匹配对应图标,组合图标与文字显示。
修改后完整代码
// 新增导入所需图标 import SendIcon from '@mui/icons-material/Send'; import ReceiveIcon from '@mui/icons-material/Receive'; import Box from '@mui/material/Box'; import TextField from '@mui/material/TextField'; import SearchIcon from '@mui/icons-material/Search'; import ClearIcon from '@mui/icons-material/Clear'; import IconButton from '@mui/material/IconButton'; import { DataGrid } from '@mui/x-data-grid'; import { useState, useEffect } from 'react'; function DataGridExample() { const [platform, setPlatform] = useState([]); const [searchText, setSearchText] = useState(''); const [rows, setRows] = useState([]); useEffect(() => { let platformList = [ { id: 1, role: 'Sender', counter_party: "Bharath", token: "1.000", date:"16-03-2022 06:20 AM", comments:'Test First Transfer' }, { id: 2, role: "Sender", counter_party: "Harish", token: "1.000" , date:"14-03-2022 08:59 AM", comments:'Testing from hosted'}, { id: 3, role: "Receiver", counter_party: "Vijay", token: "1.000", date:"14-03-2022 08:53 AM", comments:'Test First Transfer'}, ]; setPlatform(platformList); setRows(platformList); }, []); // 自定义Role列渲染逻辑 const columns = [ { field: 'role', headerName: 'Role', width: 150, renderCell: (params) => { // 根据角色匹配对应图标 const Icon = params.value === 'Sender' ? SendIcon : ReceiveIcon; // 组合图标与文字,用flex实现对齐 return ( <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}> <Icon fontSize="small" /> <span>{params.value}</span> </div> ); } }, { field: 'counter_party', headerName: 'Counter Party', width: 200 }, { field: 'token', headerName: 'Token', width: 150 }, { field: 'date', headerName: 'Date', width: 200 }, { field: 'comments', headerName: 'Comments', width: 200 } ]; function escapeRegExp(value) { return value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); } const requestSearch = (searchValue) => { const searchRegex = new RegExp(escapeRegExp(searchValue), 'i'); const filteredRows = platform.filter((row) => { return Object.keys(row).some((field) => { return searchRegex.test(row[field].toString()); }); }); setRows(filteredRows); }; return ( <div> <div style={{ height: 400, width: '100%' }}> <Box> <TextField variant="outlined" size='small' value={searchText} onChange={(e) => { setSearchText(e.target.value); requestSearch(e.target.value) }} placeholder="Search..." InputProps={{ startAdornment: <SearchIcon fontSize="small" color="action" />, endAdornment: ( <IconButton title="Clear" aria-label="Clear" size="small" style={{ visibility: searchText ? 'visible' : 'hidden', borderRadius: "57%", paddingRight: "1px", margin: "0", fontSize: "1.25rem" }} onClick={(e) => { setSearchText(''); setRows(platform) }} > <ClearIcon fontSize="small" color="action" /> </IconButton> ), }} /> </Box> <DataGrid disableColumnMenu rows={rows} columns={columns} pageSize={10} rowsPerPageOptions={[10]} /> </div> </div > ); } export { DataGridExample };
关键说明
renderCell是DataGrid的核心自定义渲染属性,params.value可获取当前单元格的原始值- 通过条件判断为不同角色绑定对应图标,使用flex布局实现图标与文字的横向对齐
- 可根据需求调整图标的大小、颜色,以及容器的间距样式
内容的提问来源于stack exchange,提问作者badcoder01
相关产品推荐
相关产品推荐

