[英]Adding React-Router Link as component to Material-UI in Typescript?
大家好,當我嘗試使用 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;
我使用 Generics 的經驗有限。 如何讓react-router
的Link
組件與 TS 中的 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.