reactjs - MUI v5 + 样式化() + ListItemButton : property 'to' /'component' does not exist

标签 reactjs typescript react-router material-ui

在从 MUI v4 到 v5 的迁移过程中,我遇到了这个障碍:在 v4 中我使用了 makeStyles(),但现在想完全迁移到 styled():我无法让 Typescript 接受具有 to=component= 属性的 styled(ListItemButton)(...) .

我在 Wrapping components 上看到并阅读了 MUI 指南这实际上让我更不清楚;诚然,我既不是 Typescript 也不是 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 问题,我发现了一个解决指南问题的问题,但似乎并没有以我可以使用的方式修复它。

我也看过并读过 MUI button with styled-components including react router Link , 但解决方案基本上是一种非 Typescript 指南版本。

Edit styled-listitembutton (更新)

最佳答案

您正在使用 Link来自 MUI 包,此 Link 只是一个 anchor 元素,但与 MUI 主题的样式集成更好,您可能想使用的 Link 来自 react-router,它具有 prop,所以将代码更改为:

import { Link } from "react-router-dom";

如果您使用 styled 并希望结果组件具有来自 react-router 的 to 属性,您可以将泛型类型参数添加到 HOC:

import { Link, LinkProps } from "react-router-dom";

const ListItemButtonLink = styled(ListItemButton)<LinkProps>(({ theme }) => ({
  // ...here be styling
}));

Codesandbox Demo

关于reactjs - MUI v5 + 样式化() + ListItemButton : property 'to' /'component' does not exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69568490/

相关文章:

reactjs - React-Native - 以编程方式更改组件的样式(无点击)

typescript - TypeScript 中奇怪的可选类属性

javascript - react browserHistory.push 给出未捕获的类型错误 : Cannot read property 'push' of undefined

reactjs - 路由器调度 onEnter

node.js - 将 ReactJs 前端 + NodeJs 后端部署到 AWS

reactjs - babel-plugin-react-css-modules 与 styleName 不匹配样式

reactjs - 如何在 React Native Bare 应用程序中使用 Expo 库?

jquery - 从 TypeScript 导入 JQuery UI

angular - promise 在我解决它并更改页面时继续工作( Protractor 测试)

javascript - React history.push 重新加载组件。希望它只加载一次