首页 > 解决方案 > 在 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

标签: reactjstypescriptreact-routermaterial-uistyled-components

解决方案


基于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>

推荐阅读