gpt4 book ai didi

reactjs - Material-UI - 如何将自定义 Prop 传递给自定义 TreeItem?

转载 作者:行者123 更新时间:2023-12-05 02:38:38 25 4
gpt4 key购买 nike

我需要将参数 category 传递给 CustomTreeItem,即 TreeItemContent
文件: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} />
);
};

我该怎么做?

第一个答案后的澄清

新代码是:

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

如何将我的自定义 Prop 传递给 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 的属性接口(interface)以消除错误:

declare module "@material-ui/lab/TreeItem" {
interface TreeItemContentProps {
myProps: string;
}
}

ContentProps 本身不能被扩充,这是 MUI API 的一个缺点,解决方法是简单地忽略它:

ContentProps={
{
myProps: "my props"
} as any
}

关于reactjs - Material-UI - 如何将自定义 Prop 传递给自定义 TreeItem?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69481071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com