使用情感/样式组件的打字稿问题

时间:2021-06-13 17:21:38

标签: css reactjs typescript styled-components emotion

当前行为:

当我想设置包装样式组件的父组件的类型时,我在使用打字稿和情绪/样式时遇到问题。

我有一个包装样式组件的父组件

const response =await fetch(url);
// button/index.tsx

import { ButtonStyled } from "./Button.styles";
import { ButtonProps } from "./Button.interface";

const Button = ({
  variant = "primary",
  ...rest
}: ButtonProps): typeof ButtonStyled => <ButtonStyled {...rest} />;

export default Button;

当我设置 Button 的返回类型( typeof ButtonStyled )时,它会出现此错误:

_Type 'ReactElement' 缺少来自类型 'StyledComponent<{ theme?: Theme; 的以下属性。作为?:元素类型; },DetailedHTMLProps, {}>': withComponent, _emotion_styles

image

这很重要,因为在另一个文件中我想扩展按钮的样式

// button/Button.styles

import styled from "@emotion/styled";

export const ButtonStyled = styled.button`
  padding: 0.4em;
  width: 100%;
  border: 0;
`;

但它不能这样做,因为它抛出了这个错误:

属性 'withComponent' 不存在于类型 '({ variant, ...rest }: ButtonProps) => StyledComponent<{ theme?: Theme;作为?:元素类型; },DetailedHTMLProps, {}>'.

环境信息:

  • import styled from "@emotion/styled"; import Button from "components/button"; export const SubmitButton = Button.withComponent` background: #333; color: #fff; `; 版本:10.2.3
  • next 版本:17.0.2
  • react 版本:11.4.0
  • @emotion/react 版本:11.3.0

1 个答案:

答案 0 :(得分:0)

您的代码存在一些问题:

  • Buttonbutton/index.tsx 函数的返回类型不是 React.Componenttypeof ButtonStyled。这是JSX.Element
  • 考虑到 Button 本身的类型是 (props: ButtonProps) => JSX.Element。这是一个函数。它绝对没有 withComponent 属性。

我猜你真正想要达到的目标是这样的:

// -------- button/Button.styles
export const ButtonStyled = styled.button`
  padding: 0.4em;
  width: 100%;
  border: 0;
`;
// -------- button/index.tsx
const Button = ({ variant = "primary", ...rest }: ButtonProps) => (
  <ButtonStyled {...rest} />
);
// --------
export const SubmitButton = styled(ButtonStyled)`
  background: #333;
  color: #fff;
`.withComponent(Button);