在从MUI v4迁移到v5的过程中,我遇到了这个障碍:在v4中,我使用了makeStyles(),但现在我想完全迁移到styled():我无法让Typescript接受具有to=和component=属性的styled(ListItemButton)(...)。
我看过并阅读过MUI关于Wrapping components的指南,它实际上让我的事情变得更不清楚;诚然,我既不是打字专家,也不是MUI向导。我的困惑是由于指南的例子不完整,比如明显缺少一些非明显的导入,似乎需要导入符号重命名,因此自动补全将不起作用或出现多个候选。
这是一个触发Typescript错误的最小化示例,参见下面的codesandbox链接。
import React from "react"
import {
Avatar,
Link,
ListItemAvatar,
ListItemButton,
styled
} from "@mui/material"
const ListItemButtonLink = styled(ListItemButton)(({ theme }) => ({
// ...here be styling
}))
interface LinkedListItemProps {
path: string
}
export const LinkedListItem = ({ path }: LinkedListItemProps) => {
return (
<ListItemButtonLink key={42} dense to={path} component={Link}>
<ListItemAvatar>
<Avatar>A</Avatar>
</ListItemAvatar>
Here Be Item
</ListItemButtonLink>
)
}我完全不知道如何让它工作,因为Guide示例也没有通过Typescript检查。
通过查看MUI问题,我发现了一个解决了Guide问题的问题,但似乎并没有以我可以使用的方式来解决它。
我也看过和读过MUI button with styled-components including react router Link,但解决方案基本上是某种非Typescript指南版本。
(更新版)
发布于 2021-10-14 09:48:42
您正在使用来自MUI包的Link,此Link只是一个锚元素,但与MUI主题有更好的样式集成,您可能想要使用的Link来自具有to属性的react-router,因此将您的代码更改为:
import { Link } from "react-router-dom";如果您使用styled并希望生成的组件具有来自react- to的属性类型,则可以将泛型类型参数添加到HOC:
import { Link, LinkProps } from "react-router-dom";
const ListItemButtonLink = styled(ListItemButton)<LinkProps>(({ theme }) => ({
// ...here be styling
}));
https://stackoverflow.com/questions/69568490
复制相似问题