【问题标题】:Can't use props for styled components with emotion-js and typescript不能使用带有情感 js 和 typescript 的样式组件的道具
【发布时间】:2021-03-30 20:25:45
【问题描述】:

这是我非常简单的组件:

import React, { ReactChild, ElementType } from 'react'
import styled from '@emotion/styled'

type WrapperPropsType = {
  size?: SizeType
}

type ButtonPropsType = {
  as?: ElementType<any>,
  size?: SizeType,
  children?: ReactChild
}

const Wrapper = styled.button<WrapperPropsType>((props: WrapperPropsType) => ({
  fontSize: FontSize[props.size],
}))

const Button = ({ as, size, children }: ButtonPropsType) => {
  return (
    <Wrapper as={as} size={size}>
        { children }
    </Wrapper>
  )
}

我的.tsconfig

{
  "compilerOptions": {
    "types": ["node", "@emotion/react"],
    "declaration": true,
    "declarationDir": "build",
    "module": "esnext",
    "target": "es5",
    "sourceMap": true,
    "jsx": "preserve",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true
  },
  "include": ["src/**/*"],
  "exclude": [
    "node_modules",
    "build",
    "src/**/*.test.tsx"
  ]
}

但在编译时出现下一个错误:

错误:src/components/Button/Button.tsx(18,30):语义错误 TS2339:属性“大小”不存在于类型“{主题?:主题;作为?:元素类型; } & Pick, "form" | ... 265 更多... | "onTransitionEndCapture"> & { ...; }'。

我做错了什么?感谢您的帮助

包版本: @emotion/react 版本:11.1.2 @emotion/styled 版本:11.0.0 typescript 版本:4.1.3

【问题讨论】:

    标签: reactjs typescript styled-components emotion emotion-js


    【解决方案1】:

    我通过将rollup-plugin-typescript2 替换为@rollup/plugin-typescript 设法解决了这个问题。代码中没有错误。

    【讨论】:

      【解决方案2】:

      您在WrapperPropsType 中定义了size,但没有使用它。添加它,它会工作

      const Button = ({ as, size, children }: ButtonPropsType & WrapperPropsType) => {
      

      【讨论】:

      • 我在 ButtonPropsType 中也有 size,所以它已经定义好了,不幸的是,添加 &amp; WrapperPropsType 并没有改变任何东西
      • 检查您是否使用了正确的ButtonPropsType。因为{ theme?: Theme; as?: ElementType; } &amp; Pick&lt;DetailedHTMLProps&lt;ButtonHTMLAttributes, HTMLButtonElement&gt;{ as?: ElementType&lt;any&gt;, size?: SizeType, children?: ReactChild } 不一样
      猜你喜欢
      • 2020-08-08
      • 2021-11-01
      • 2020-07-12
      • 2019-05-20
      • 2019-04-13
      • 2021-06-19
      • 2020-05-01
      • 2021-12-31
      • 2021-12-13
      相关资源
      最近更新 更多