繁体   English   中英

将 Typescript 与样式化组件和 Material UI 结合使用

[英]Using Typescript with Styled Components and Material UI

将 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 ... | "variant"> & Partial<...>, "form" | ... 286 更多... | “变体”> & { ...; } & { ...; }) | (IntrinsicAttributes & ... 3 more ... & { ...; })'

当您直接传入如下所示的道具时,此错误就会消失。 即使在 Styled MUI 元素上使用 0 个道具和 0 个子项,也会出现错误。

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

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

对于早期版本,从本教程中,尝试强制执行StyledButton的类型:

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

我不小心通过安装@types/styled-components / styled-components解决了这个问题,无论如何我都需要让 styled/theme/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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM