升级Kendo React至v11.x后,如何向Grid自定义cell传函数或属性?
Kendo React 11.x Grid 自定义单元格迁移方案
Kendo React 11.x对Grid组件做了重大重构,原有的函数式cell属性语法确实已被移除,但提供了更规范的替代方案来实现自定义单元格和传递额外属性,具体如下:
传递额外属性给自定义单元格
现在通过列配置的props字段来传递自定义属性,自定义单元格组件可以通过props.column.props获取这些额外参数:
示例代码
// 自定义单元格组件 const CustomCell = (props) => { // 提取通过column.props传递的自定义属性 const { customTitle, onRowAction } = props.column.props; return ( <td> <strong>{customTitle}:</strong> {props.dataItem.fieldName} <button onClick={() => onRowAction(props.dataItem)}>执行操作</button> </td> ); }; // Grid列配置 <Grid data={yourDataSource}> <Column field="fieldName" cell={CustomCell} // 在这里传递额外属性 props={{ customTitle: "自定义标题", onRowAction: (item) => console.log("处理行数据:", item) }} /> </Grid>
原函数式cell的替代实现
如果之前使用函数式cell是为了动态渲染内容,现在可以将逻辑封装到自定义单元格组件内部,或者通过column.props传入动态渲染函数:
基础替代写法(替代简单函数式cell)
// 原10.x写法(已失效) <Column field="status" cell={(props) => ( <td className={props.dataItem.status === "active" ? "text-green" : "text-gray"}> {props.dataItem.status === "active" ? "已激活" : "已禁用"} </td> )} /> // 11.x替代写法 const StatusCell = (props) => { const statusClass = props.dataItem.status === "active" ? "text-green" : "text-gray"; const statusText = props.dataItem.status === "active" ? "已激活" : "已禁用"; return <td className={statusClass}>{statusText}</td>; }; <Column field="status" cell={StatusCell} />
灵活动态渲染方案
如果需要更灵活的动态逻辑,可以把渲染逻辑作为属性传入:
const DynamicContentCell = (props) => { const { renderContent } = props.column.props; return <td>{renderContent(props.dataItem)}</td>; }; <Column field="amount" cell={DynamicContentCell} props={{ renderContent: (item) => { return item.amount > 1000 ? ( <span style={{ color: "red" }}>{item.amount.toFixed(2)}</span> ) : ( item.amount.toFixed(2) ); } }} />
额外提示
- TypeScript项目中,建议让自定义单元格组件接收
CellProps类型,确保类型匹配:import { CellProps } from "@progress/kendo-react-grid"; const CustomCell = (props: CellProps<YourDataItemType>) => { // ...组件逻辑 }; - 若需要访问Grid的全局状态(如排序、分页信息),可以使用
useGridContext钩子获取。
内容的提问来源于stack exchange,提问作者Ryan
相关产品推荐
相关产品推荐

