reactjs - 在 Typescript 中将 React-Router Link 作为组件添加到 Material-UI?
问题描述
大家好,当我尝试使用 Material UI 的component
道具替换组件的基本 html 元素时,我遇到了以下错误。
错误
Type 'Props' is not generic.
这源于以下问题:https ://github.com/mui-org/material-ui/issues/15827 (ButtonBaseProps 不接受组件属性)
这个假定的修复写在此处的文档中:https ://material-ui.com/guides/typescript/#usage-of-component-prop
“现在 CustomComponent 可以与应该设置为 'a' 的组件道具一起使用。此外,CustomComponent 将具有 HTML 元素的所有道具。
Typography 组件的其他道具也将出现在 CustomComponent 的道具中。可以有通用的 CustomComponent 来接受任何 React 组件、自定义和 HTML 元素。”
function GenericCustomComponent<C extends React.ElementType>(
props: TypographyProps<C, { component?: C }>,
) {
/* ... */
}
瓷砖.tsx
import React from 'react';
import { Button, ButtonProps } from '@material-ui/core';
import { Link } from 'react-router-dom';
import styled from 'styled-components';
const StyledButton = styled(Button)`
width: 100%;
`;
interface Props extends ButtonProps {
children: string;
to: string;
}
const Tile = ({ children, to }: Props<Link, { component: Link }>) => (
<StyledButton component={Link} to={to} variant="contained" color="primary">
{children}
</StyledButton>
);
export default Tile;
我使用泛型的经验有限。如何让Link
组件在 TS 中react-router
使用 Styled MaterialUI ?button
解决方案
基于https://material-ui.com/guides/typescript/#usage-of-component-prop
这就是我最终使用的
import { Button, ButtonProps } from "@material-ui/core";
const AnyComponentButton = <C extends React.ElementType>(
props: ButtonProps<C, { component?: C }>
) => {
return <Button {...props} />;
};
import { Link as RouterLink } from "react-router-dom";
...
<AnyComponentButton
component={RouterLink}
to={'/account'}
>
Go to Account
</AnyComponentButton>
推荐阅读
- mysql - Django 会为模型获取错误的 content_type_id 吗?
- python - Python 播放音频与 cv2 视频同步
- linux - 禁用崩溃 Wine Debian Linux
- spring - 在非弹簧管理的 bean 上应用方面
- powerbi - Powerbi Variance YTD - 财政年度
- three.js - ThreeJS 雾或着色器或照明
- python - Tkinter 回调中的异常(使用 Python Turtle)
- javascript - React 中生成的表的键定义
- visual-studio-2017 - Nuget 包指南
- javascript - 带有关键帧和 css 变量的 stroke-dashoffset 动画