reactjs - MUI styled kan inte skicka komponentprop till Typography i typescript
Använder MUI med TypeScript och vill använda styled från MUI också. När jag skickar komponentprop till den stylade komponenten får jag ett fel från TypeScript-sandlådan nedan, kanske någon vet en lösning.
https://codesandbox.io/s/material-demo-forked-lxdrj?file=/demo.tsx
Svar #1
Du måste manuellt lägga till 'component'-prop.
Från https://mui.com/material-ui/guides/typescript/#complications-with-the-component-prop
import React from "react";
import type { TypographyProps } from "@material-ui/core";
import { styled } from "@material-ui/core/styles";
import Typography from "@material-ui/core/Typography";
type MyT = React.ComponentType<TypographyProps<"span", { component: "span" }>>;
const MyTypography: MyT = styled(Typography)({
background: "linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)",
border: 0,
borderRadius: 3,
boxShadow: "0 3px 5px 2px rgba(255, 105, 135, .3)",
color: "white",
height: 48,
padding: "0 30px"
});
export default function StyledComponents() {
return (
<MyTypography component="span">Styled with styled-components API</MyTypography>
);
}
Svar #2
Du kan använda generisk typparameter i HOC skapad av styled:
import { styled } from '@mui/material/styles';
import Typography from '@mui/material/Typography';
type ExtraProps = {
component: React.ElementType;
};
const MyTypography = styled(Typography)<ExtraProps>({
// ...
});