【问题标题】:Adding React-Router Link as component to Material-UI in Typescript?在 Typescript 中将 React-Router Link 作为组件添加到 Material-UI?
【发布时间】:2021-04-11 00:18:24
【问题描述】:

大家好,当我尝试使用 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 组件的其他 props 也会出现在 CustomComponent 的 props 中。 可以有通用的 CustomComponent 来接受任何 React 组件、自定义和 HTML 元素。"

function GenericCustomComponent<C extends React.ElementType>(
  props: TypographyProps<C, { component?: C }>,
) {
  /* ... */
}

Tile.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;

我使用泛型的经验有限。如何让react-routerLink 组件与TS 中的Styled MaterialUI button 一起使用?

【问题讨论】:

  • 您可以尝试简单地将 Link 转换为 ElementType,而不使用泛型 &lt;StyledButton component={Link as React.ElementType}

标签: reactjs typescript react-router material-ui styled-components


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-10-17
    • 2018-11-14
    • 1970-01-01
    • 2021-02-21
    • 2017-03-15
    • 2020-11-18
    • 2017-04-05
    • 2017-08-19
    • 2020-11-22
    相关资源
    最近更新 更多