React中CSSProperties类型cellStyle与Properties<string|number>不兼容问题
React中cellStyle属性类型不匹配问题解决思路
错误提示:类型'(params: any) => CSSProperties'与类型'Properties<string | number>'无共同属性。是否想要调用它?
问题
为何React中类型为CSSProperties的cellStyle属性无法生效?如何让它适配Properties<string | number>类型?
相关代码示例
export const fields: GridFieldsConfiguration[] = [ { ...defaultColDefs, field: 'amInitials', displayNameRule: 'Asset Manager', flex: 1.1, minWidth: 75, cellStyle: (params: any): any => { getCellStyle(params, 'amInactive') } } ]; const isDisabledbStyle = { color: '#FF0000' }; const getCellStyle = ((params: any, inactiveCol: string): CSSProperties => { console.log(params); if (params?.api?.getValue(inactiveCol, params.node) === true) { return isDisabledbStyle; } else { return isDisabledbStyle; } } );
类型说明
cellStyle的类型为CSSProperties,它是CSS.Properties<string | number>的扩展,相关定义如下:
export interface GridFieldConfiguration extends FieldConfiguration { cellStyle?: CSSProperties; } export interface CSSProperties extends CSS.Properties<string | number> { /** * The index signature was removed to enable closed typing for style * using CSSType. You're able to use type assertion or module augmentation * to add properties or an index signature of your own. */ }
Properties接口定义:
export interface Properties<TLength = string | 0> extends StandardProperties<TLength>, VendorProperties<TLength>, ObsoleteProperties<TLength>, SvgProperties<TLength> {}
问题根源
GridFieldConfiguration里的cellStyle要求是静态的CSSProperties样式对象,但你现在给的是一个返回样式的函数——函数类型和静态样式对象类型完全不兼容,这就是报错的核心原因,同时因为类型不匹配,样式自然也无法生效。另外你的函数还存在一个小问题:没有写return,就算类型对了,也会返回undefined导致样式失效。
解决方案
方案1:让类型支持动态函数(如果组件允许)
先确认你使用的网格组件是否支持cellStyle接收函数(不少表格组件都支持这种动态样式写法)。如果支持,修改GridFieldConfiguration的类型定义,让cellStyle同时兼容静态对象和函数:
export interface GridFieldConfiguration extends FieldConfiguration { cellStyle?: CSSProperties | ((params: any) => CSSProperties); }
同时修正你的函数,补上return:
cellStyle: (params: any) => { return getCellStyle(params, 'amInactive'); }
方案2:改用静态样式或单元格渲染器(如果组件只支持静态样式)
如果你的网格组件只接受静态样式对象,有两种处理方式:
- 静态场景直接传对象:如果不需要动态判断,直接把样式对象赋值给
cellStyle:
cellStyle: isDisabledbStyle
- 动态场景用单元格渲染器:如果需要根据单元格数据动态设置样式,改用组件提供的单元格渲染器(
cellRenderer)来实现:
{ ...defaultColDefs, field: 'amInitials', displayNameRule: 'Asset Manager', flex: 1.1, minWidth: 75, cellRenderer: (params: any) => { const style = getCellStyle(params, 'amInactive'); // 把样式对象转成行内样式字符串 const styleStr = Object.entries(style) .map(([key, value]) => `${key}: ${value}`) .join('; '); return `<div style="${styleStr}">${params.value}</div>`; } }
内容的提问来源于stack exchange,提问作者Conrad Addo
相关产品推荐
相关产品推荐

