【问题标题】:MUI styled cannot pass component prop to Typography in typescript样式化的 MUI 无法在 typescript 中将组件道具传递给 Typography
【发布时间】:2021-05-28 23:53:07
【问题描述】:

将 MUI 与 typescript 一起使用,并且还想使用 MUI 中的 styled。将组件道具传递给样式化组件时,我从下面的打字稿沙箱中收到错误,也许有人知道解决方法。

https://codesandbox.io/s/material-demo-forked-lxdrj?file=/demo.tsx

【问题讨论】:

    标签: reactjs typescript material-ui styled-components


    【解决方案1】:

    您必须手动添加“组件”属性。

    来自https://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>
      );
    }
    

    【讨论】:

    • 很好,不知何故错过了文档欢呼队友!
    【解决方案2】:

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

    import { styled } from '@mui/material/styles';
    import Typography from '@mui/material/Typography';
    
    type ExtraProps = {
      component: React.ElementType;
    };
    const MyTypography = styled(Typography)<ExtraProps>({
      // ...
    });
    

    现场演示

    【讨论】:

    • 这行得通,虽然 imo 需要它很可笑
    • @MarksCode 看到我更新的答案,我不知道为什么事情之前这么复杂。 IIRC 的问题是 component 是一个非常常见的道具,并且在所有 MUI 组件中都可用,因此类型定义在其他地方定义为更可重用,这会产生不幸的边缘情况。
    • 如果它已经在组件上可用,您必须定义该道具仍然很奇怪
    【解决方案3】:
    const StyledTypography = styled<any>(Typography)`
    margin: 12px 0;`;
    

    这对我有用...
    这是示例⇓
    https://codesandbox.io/s/styled-typography-trb0v?file=/src/App.tsx:76-148

    【讨论】:

      猜你喜欢
      • 2022-01-24
      • 2017-10-20
      • 2020-10-28
      • 2020-08-12
      • 2017-08-17
      • 2019-09-23
      • 2018-02-03
      • 2021-11-02
      • 2020-04-10
      相关资源
      最近更新 更多