【发布时间】: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-router 的Link 组件与TS 中的Styled MaterialUI button 一起使用?
【问题讨论】:
-
您可以尝试简单地将 Link 转换为 ElementType,而不使用泛型
<StyledButton component={Link as React.ElementType}
标签: reactjs typescript react-router material-ui styled-components