【问题标题】:How to type a button with react-router-dom Link in MUI v5如何在 MUI v5 中使用 react-router-dom 链接键入按钮
【发布时间】:2021-10-02 22:09:07
【问题描述】:

问题

我正在从 MUI v4 迁移到 v5,并且在使用 styled 函数设置 Button 组件的样式时遇到问题。出于某种原因,当我使用MyButton 而不是Button 时,编译器会出现component 属性的问题。

错误信息

Type '{ children: string; component: <S = unknown>(props: LinkProps<S> & RefAttributes<HTMLAnchorElement>) => ReactElement<any, string | JSXElementConstructor<any>> | null; to: string; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; classes?: Partial<ButtonClasses> | undefined; color?: "inherit" | "primary" | ... 5 more ... | undefined; ... 9 more ...; variant?: "text" | ... 2 more ... | undefined; } & ... 5 more ... & { ...; }'.
  Property 'component' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; classes?: Partial<ButtonClasses> | undefined; color?: "inherit" | "primary" | ... 5 more ... | undefined; ... 9 more ...; variant?: "text" | ... 2 more ... | undefined; } & ... 5 more ... & { ...; }'.

我的代码

import { alpha, Button, styled } from "@mui/material";
import React from "react";
import { Link, HashRouter as Router } from 'react-router-dom';
import "./styles.css";

export default function App() {

  const MyButton = styled(Button)(({ theme }) => ({
    color: 'white',
    margin: theme.spacing(1),
    backgroundColor: alpha(theme.palette.common.white, 0.25),
    '&:hover': {
      backgroundColor: alpha(theme.palette.common.white, 0.35),
    },
  }));

  return (
    <Router basename="/">
      <div className="App">
        <MyButton component={Link} to="/"> // why doesn't this work?
          My Button
        </MyButton>
      </div>
    </Router>
  );
}

代码沙盒

CodeSandbox Link Here

【问题讨论】:

    标签: reactjs typescript material-ui


    【解决方案1】:

    您缺少 Link 组件的 props 类型定义。要修复它,请安装 @types/react-router-dom 包并在使用 styled 时声明您的 HOC 道具类型,如下所示:

    import { Link, HashRouter as Router, LinkProps } from "react-router-dom";
    
    const MyButton = styled(Button)<LinkProps>(({ theme }) => ({
      // your link styles
    }));
    
    <MyButton component={Link} to="/route">
      My Button
    </MyButton>
    

    现场演示

    【讨论】:

      【解决方案2】:

      这似乎对我有用

      import { Link as RouterLink } from 'react-router-dom';
      import { Link} from '@mui/material';
      

      ...

      <Link 
          to={slug}
          component={RouterLink}
          variant="button"
          color="secondary"
          >
      Read More
      </Link>
      

      【讨论】:

        猜你喜欢
        • 2020-11-05
        • 1970-01-01
        • 2019-01-09
        • 2021-07-19
        • 1970-01-01
        • 1970-01-01
        • 2021-01-09
        • 2021-12-28
        • 2017-07-16
        相关资源
        最近更新 更多