我需要传递一个参数category
到CustomTreeItem
,即TreeItemContent
。
Doc: https://mui.com/ru/api/tree-item/
import TreeItem, {
TreeItemProps,
useTreeItem,
TreeItemContentProps,
} from '@material-ui/lab/TreeItem';
interface CatProps {
name: string,
id: string,
}
interface CatItemContentProps extends TreeItemContentProps {
category: CatProps,
}
const CustomContent = React.forwardRef(function CustomContent(
props: CatItemContentProps,
ref,
) {
const { category } = props;
console.log(category); // undefined
return <></>;
}
);
interface CatItemProps extends TreeItemProps {
category: CatProps,
}
const CustomTreeItem = (props: CatItemProps) => {
return (
<TreeItem ContentComponent={CustomContent} {...props} />
);
};
我该怎么做?
Сlarifications在第一个答案之后
新代码是:
const CustomContent = React.forwardRef(function CustomContent(
props: TreeItemContentProps,
ref
) {
return (
<div ref={ref as React.Ref<HTMLDivElement>}>
{props.label} {props.myProps}
</div>
);
});
const CustomTreeItem = (props: TreeItemProps) => {
return <TreeItem ContentComponent={CustomContent} {...props} />;
};
export default function App() {
return (
<TreeView>
<CustomTreeItem
nodeId="1"
label="Applications"
ContentProps={{
myProps: "my props"
}}
></CustomTreeItem>
</TreeView>
);
}
我在codesandbox没问题:https://codesandbox.io/s/clever-volhard-km9xf?file=/src/App.tsx
但是如果我的代码有一个新的错误:
Type '{ myProps: string; }' is not assignable to type 'HTMLAttributes<HTMLElement>'.
Object literal may only specify known properties, and 'myProps' does not exist in type 'HTMLAttributes<HTMLElement>'
谷歌给了我同样的问题从另一个人:
https://issueexplorer.com/issue/mui-org/material-ui/28668
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/1349b640d4d07f40aa7c1c6931f18e3fbf667f3a/types/react/index.d.ts#L1743
如何将我的自定义props传递给ContentProps?
使用ContentProps
props,它将与原来的TreeItemContentProps
合并
<CustomTreeItem
nodeId="1"
label="Applications"
ContentProps={{
myProps: "my props",
}}
>
const CustomContent = React.forwardRef(function CustomContent(
props: TreeItemContentProps,
ref
) {
console.log(props.myProps); // "my props"
编辑:对于typescript用户,您还需要增加TreeItemContent
的prop接口,以删除错误:
declare module "@material-ui/lab/TreeItem" {
interface TreeItemContentProps {
myProps: string;
}
}
ContentProps
本身不能被增强,这是MUI API的一个缺点,一个解决方法是简单地忽略它:
ContentProps={
{
myProps: "my props"
} as any
}
按照当前文档执行以下步骤
我找到了下面文档中提到的方法
代码:https://github.com/mui/material-ui/blob/512896973499adbbda057e7f3685d1b23cc02de9/docs/src/components/productX/XTreeViewDemo.tsx
步骤1在自定义组件上添加TreeItemContentProps属性
const CustomContentChildContent = React.forwardRef(function CustomContent(
props: TreeItemContentProps & { myCustomData?: string },
ref,
)
步骤2添加自定义属性到与TreeItemProps
const CustomTreeItemChild = (
props: TreeItemProps & {
ContentProps?: { myCustomData?: string };
},
) => <StyledTreeItem ContentComponent={CustomContentChildContent} {...props} />;
步骤3
添加属性的组件你调用
<CustomTreeItemChild nodeId="3" label={item.name} ContentProps={{ myCustomData: 'anything-i-can-pass' }} />