Material-UI 如何给自定义TreeItem传自定义props并解决ContentProps类型报错
解决方案
一、基础实现:传递category参数到CustomContent
TreeItem不会自动将CustomTreeItem的自定义属性透传给ContentComponent,你需要主动提取category后通过ContentProps传递:
import TreeItem, { TreeItemProps, TreeItemContentProps, } from '@material-ui/lab/TreeItem'; import React from 'react'; interface CatProps { name: string, id: string, } // 扩展自定义内容组件的Props类型 interface CatItemContentProps extends TreeItemContentProps { category: CatProps, } const CustomContent = React.forwardRef<HTMLDivElement, CatItemContentProps>(function CustomContent( props, ref, ) { const { category } = props; console.log(category); // 可正常获取值 return <div ref={ref}>{category.name}</div>; } ); // 扩展自定义TreeItem的Props类型 interface CatItemProps extends TreeItemProps { category: CatProps, } const CustomTreeItem = (props: CatItemProps) => { // 解构自定义属性和原生TreeItem属性 const { category, ...rest } = props; return ( <TreeItem ContentComponent={CustomContent} // 将自定义参数合并到ContentProps传递给内容组件 ContentProps={{ ...rest.ContentProps, category }} {...rest} /> ); };
使用示例:
<CustomTreeItem nodeId="1" label="测试分类" category={{id: 'cat1', name: '前端开发'}} />
二、解决ContentProps自定义属性TS类型报错
你本地报错是因为MUI默认将ContentProps类型约束为HTMLAttributes<HTMLElement>,不识别自定义属性,两种解决方案任选:
方案1:局部类型断言(无全局污染,推荐)
传递ContentProps时直接断言为你自定义的内容组件Props类型:
interface CustomContentProps extends TreeItemContentProps { myProps: string } const CustomContent = React.forwardRef<HTMLDivElement, CustomContentProps>(function CustomContent( props, ref ) { return ( <div ref={ref}> {props.label} {props.myProps} </div> ); }); const CustomTreeItem = (props: TreeItemProps & { myProps?: string }) => { const { myProps, ...rest } = props return <TreeItem ContentComponent={CustomContent} ContentProps={{ ...rest.ContentProps, myProps } as CustomContentProps} // 此处添加类型断言 {...rest} />; };
方案2:全局扩展类型(适合多场景复用)
在项目的全局类型声明文件(如global.d.ts)中添加如下声明,扩展MUI的TreeItemContentProps类型允许自定义属性:
declare module '@material-ui/lab/TreeItem' { interface TreeItemContentProps { [key: string]: any } }
添加后所有ContentProps都支持传入自定义属性,不会再触发类型错误。
内容的提问来源于stack exchange,提问作者user3713526
相关产品推荐
相关产品推荐

