gpt4 book ai didi

reactjs - 如何在 MUI v5 中使用 react-router-dom 链接键入按钮

转载 作者:行者123 更新时间:2023-12-05 03:37:09 26 4
gpt4 key购买 nike

问题

我正在从 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

最佳答案

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

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>

现场演示

Codesandbox Demo

关于reactjs - 如何在 MUI v5 中使用 react-router-dom 链接键入按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69420620/

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