reactjs MUI样式无法将组件属性传递给 typescript 中的排版

smdncfj3  于 2023-01-30  发布在  React
关注(0)|答案(3)|浏览(150)

使用MUI和typescript,并且想使用来自MUI的styled。当把组件属性传递给样式化组件时,我从下面的typescript沙箱中得到一个错误,也许有人知道一个解决方法。
https://codesandbox.io/s/material-demo-forked-lxdrj?file=/demo.tsx

snvhrwxg

snvhrwxg1#

您必须手动添加"组件"属性。
来自www.example.comhttps://material-ui.com/guides/typescript/#usage-of-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>
  );
}
j8ag8udp

j8ag8udp2#

可以在styled创建的HOC中使用泛型类型参数:

import { styled } from '@mui/material/styles';
import Typography from '@mui/material/Typography';

type ExtraProps = {
  component: React.ElementType;
};
const MyTypography = styled(Typography)<ExtraProps>({
  // ...
});

现场演示

but5z9lq

but5z9lq3#

与@GitGitBoom的思想相同,但不需要定义类型。您可以使用MUI Typescript Guide中描述的解决方案,只需将样式化组件转换为typeof Typography

import React from "react";
import { styled } from "@material-ui/core/styles";
import Typography from "@material-ui/core/Typography";

const MyTypography = 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"
}) as typeof Typography;

export default function StyledComponents() {
  return (
    <MyTypography component="span">
      Styled with styled-components API
    </MyTypography>
  );
}

相关问题