【问题标题】:Using Typescript with Styled Components and Material UI将 Typescript 与样式化组件和 Material UI 一起使用
【发布时间】:2019-09-01 07:37:45
【问题描述】:

将 Typescript 与 MUI+Styled-Components 一起使用,由于类型错误,您必须直接将 props 传递给 MUI 元素......

const Index = () => {
  return (
      <StyledButton
        variant="contained"
      >
        Hello World
      </StyledButton>
   )}


const StyledButton = styled(Button)`
  background: red;
  color: white;
`;

但是,这会报错:

键入'{孩子:字符串;变体:“包含”; }' 不可分配给类型 '(IntrinsicAttributes & Pick>) | PropsWithChildren,“形式” | “风格” | “标题” | ... 284 更多... | "变体"> & 部分<...>, "形式" | ... 286 更多... | “变体”> & { ...; } & { ...; }) | (IntrinsicAttributes & ... 还有 3 个 ... & { ...; })'

当你像下面这样直接传入 props 时,这个错误就会消失。即使在 Styled MUI 元素上使用 0 个道具和 0 个子元素,也会出现错误。

const StyledButton = styled(props => <Button {...props} />)`
  background: red;
  color: white;
`;

【问题讨论】:

    标签: javascript reactjs typescript material-ui styled-components


    【解决方案1】:

    我不小心通过安装 @types/styled-components / styled-components 解决了这个问题,无论如何我都需要它来让样式/主题/TS 都很好地一起玩:

    import React from "react";
    import styled from "styled-components";
    import { Theme, useTheme } from "@material-ui/core/styles";
    import Button from "@material-ui/core/Button";
    
    const StyledCustomButton: React.FC<{
      theme: Theme;
    }> = styled(({ ...props }) => <Button {...props}>Test</Button>)`
      && {
        padding-bottom: ${(props) => props.theme.spacing(2)}px;
      }
    `;
    
    const CustomButton: React.FC = () => {
      const theme: Theme = useTheme();
      return <StyledCustomButton theme={theme} />;
    };
    
    export default CustomButton;
    

    【讨论】:

      【解决方案2】:

      这应该适用于 MUI >= 4.*

      对于早期版本,从 this tutorial 开始,尝试强制使用 StyledButton 的类型:

      const StyledButton = styled(Button)`
        background: red;
        color: white;
      ` as typeof(Button);
      

      【讨论】:

        猜你喜欢
        • 2021-01-20
        • 2022-06-22
        • 2018-09-14
        • 2021-09-11
        • 1970-01-01
        • 1970-01-01
        • 2017-09-19
        • 2021-05-19
        • 2020-03-31
        相关资源
        最近更新 更多