ReactJS项目中如何修改Material Table选中复选框的颜色?
修改Material Table选中状态复选框颜色的方法
嘿,刚好我之前做项目的时候也折腾过Material Table的复选框样式,给你分享两个靠谱的解决办法,适配你的代码:
方案1:组件级自定义样式(推荐)
这个方法只会影响当前组件的复选框,不会干扰项目里其他的Material-UI组件,灵活性拉满。
用makeStyles实现(Material-UI v4及以下)
先导入makeStyles,然后定义自定义样式:
import { makeStyles } from '@material-ui/core/styles'; import MaterialTable from 'material-table'; const useStyles = makeStyles({ customSelectedCheckbox: { // 选中状态的颜色 '&.Mui-checked': { color: '#ff4081', // 换成你想要的颜色,比如这里用粉色 }, // 表头全选时的半选中状态(可选) '&.MuiCheckbox-indeterminate': { color: '#ff4081', } } }); function BasicSelection() { const classes = useStyles(); return ( <MaterialTable title="Basic Selection Preview" columns={[ { title: 'Name', field: 'name' }, { title: 'Surname', field: 'surname' }, { title: 'Birth Year', field: 'birthYear', type: 'numeric' }, { title: 'Birth Place', field: 'birthCity', lookup: { 34: 'İstanbul', 63: 'Şanlıurfa' }, }, ]} data={[ { name: 'Mehmet', surname: 'Baran', birthYear: 1987, birthCity: 63 }, { name: 'Zerya Betül', surname: 'Baran', birthYear: 2017, birthCity: 34 }, ]} options={{ selection: true }} // 自定义Checkbox组件,应用我们的样式 components={{ Checkbox: (props) => ( <props.Checkbox {...props} className={classes.customSelectedCheckbox} /> ) }} /> ) }
用sx属性实现(Material-UI v5)
如果你的项目用的是Material-UI v5,直接用sx更简洁,不用额外导入makeStyles:
function BasicSelection() { return ( <MaterialTable title="Basic Selection Preview" columns={[ { title: 'Name', field: 'name' }, { title: 'Surname', field: 'surname' }, { title: 'Birth Year', field: 'birthYear', type: 'numeric' }, { title: 'Birth Place', field: 'birthCity', lookup: { 34: 'İstanbul', 63: 'Şanlıurfa' }, }, ]} data={[ { name: 'Mehmet', surname: 'Baran', birthYear: 1987, birthCity: 63 }, { name: 'Zerya Betül', surname: 'Baran', birthYear: 2017, birthCity: 34 }, ]} options={{ selection: true }} components={{ Checkbox: (props) => ( <props.Checkbox {...props} sx={{ '&.Mui-checked': { color: '#ff4081' }, '&.MuiCheckbox-indeterminate': { color: '#ff4081' } }} /> ) }} /> ) }
方案2:全局样式覆盖(适合全项目统一修改)
如果你希望项目里所有Material Table的选中复选框都用同一个颜色,可以在全局CSS文件里加这段样式:
/* 普通行选中的复选框 */ .MuiTableSelectionCell-checkbox .Mui-checked { color: #ff4081; } /* 表头全选的半选中状态 */ .MuiTableSelectionCell-checkbox .MuiCheckbox-indeterminate { color: #ff4081; }
不过要注意,这个会影响所有Material Table的复选框,所以如果只是个别组件需要修改,还是用方案1更稳妥。
内容的提问来源于stack exchange,提问作者theWanderer
相关产品推荐
相关产品推荐

