use*_*526 3 typescript reactjs material-ui
我需要将一个参数传递category给CustomTreeItemis TreeItemContent。
\n文档: https: //mui.com/ru/api/tree-item/
import TreeItem, {\n TreeItemProps,\n useTreeItem,\n TreeItemContentProps,\n} from \'@material-ui/lab/TreeItem\';\n\ninterface CatProps {\n name: string,\n id: string,\n}\n\ninterface CatItemContentProps extends TreeItemContentProps {\n category: CatProps,\n}\n\nconst CustomContent = React.forwardRef(function CustomContent(\n props: CatItemContentProps,\n ref,\n ) {\n const { category } = props;\n console.log(category); // undefined\n\n return <></>;\n }\n);\n\n\ninterface CatItemProps extends TreeItemProps {\n category: CatProps,\n}\n\nconst CustomTreeItem = (props: CatItemProps) => {\n return (\n <TreeItem ContentComponent={CustomContent} {...props} />\n );\n};\n\nRun Code Online (Sandbox Code Playgroud)\n我该怎么做?
\n第一个答案后的\xd0\xa1说明
\n新代码是:
\nconst CustomContent = React.forwardRef(function CustomContent(\n props: TreeItemContentProps,\n ref\n) {\n return (\n <div ref={ref as React.Ref<HTMLDivElement>}>\n {props.label} {props.myProps}\n </div>\n );\n});\n\nconst CustomTreeItem = (props: TreeItemProps) => {\n return <TreeItem ContentComponent={CustomContent} {...props} />;\n};\n\nexport default function App() {\n return (\n <TreeView>\n <CustomTreeItem\n nodeId="1"\n label="Applications"\n ContentProps={{\n myProps: "my props"\n }}\n ></CustomTreeItem>\n </TreeView>\n );\n}\nRun Code Online (Sandbox Code Playgroud)\n我已经在codesandbox中制作它并且工作正常:
\n https://codesandbox.io/s/clever-volhard-km9xf?file=/src/App.tsx
但我的代码有一个新错误:
\nType \'{ myProps: string; }\' is not assignable to type \'HTMLAttributes<HTMLElement>\'.\nObject literal may only specify known properties, and \'myProps\' does not exist in type \'HTMLAttributes<HTMLElement>\'\nRun Code Online (Sandbox Code Playgroud)\n谷歌给了我另一个人同样的问题:
\n https://issueexplorer.com/issue/mui-org/material-ui/28668
如何将自定义道具传递给 ContentProps?
\n使用ContentPropsprops,它会和原来合并TreeItemContentProps
<CustomTreeItem
nodeId="1"
label="Applications"
ContentProps={{
myProps: "my props",
}}
>
Run Code Online (Sandbox Code Playgroud)
const CustomContent = React.forwardRef(function CustomContent(
props: TreeItemContentProps,
ref
) {
console.log(props.myProps); // "my props"
Run Code Online (Sandbox Code Playgroud)
编辑:对于打字稿用户,您还需要增强 prop 接口TreeItemContent以消除错误:
declare module "@material-ui/lab/TreeItem" {
interface TreeItemContentProps {
myProps: string;
}
}
Run Code Online (Sandbox Code Playgroud)
它ContentProps本身无法增强,这是 MUI API 的一个缺点,解决方法就是忽略它:
ContentProps={
{
myProps: "my props"
} as any
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3723 次 |
| 最近记录: |