【问题标题】:Typescript, React and Recompose issuesTypescript、React 和 Recompose 问题
【发布时间】:2019-02-21 16:26:01
【问题描述】:

提前为这个模糊的标题道歉,我的问题很难回答。

我正在尝试同时使用 React、Recompose 和 Typescript,但是在尝试将 props 传递到我的组件时出现以下错误:

[ts] Property 'bar' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<{}, any, any>> & Readonly<{ children?: ReactNode; }> & Readonly<{}>'.

组件是这样导入的:

import TestComponent from './TestComponent'

并像这样调用:

<TestComponent bar="hello"/>

这是我的组件文件夹的结构:

├── TestComponent.tsx
├── TestComponentContainer.ts
└── index.ts

index.ts如下:

import TestComponentContainer from './TestComponentContainer'

export default TestComponentContainer

TestComponent.jsx如下:

import * as React from 'react'

interface IProps {
  foo: string
  bar: string
}

const TestComponent: React.SFC<IProps> = ({ foo, bar }) => (
  <div>
    <p>{foo}</p>
    <p>{bar}</p>
  </div>
)

export default TestComponent

TestComponentContainer.ts如下:

import { compose, withProps } from 'recompose'

import TestComponent from './TestComponent'

export default compose(
  withProps({
    foo: 'stringy string string',
  }),
)(TestComponent)

我知道我错过了某种类型声明,用于传递正在传递的道具,但我一生都无法弄清楚我应该做什么。

编辑:

此外,如何使用嵌套方法做到这一点:

export default compose(
  setDisplayName('PlayerCardContainer'),
  withMutation(mutation),
  withHandlers(createHandlers),
)(PlayerCard)

【问题讨论】:

    标签: javascript reactjs typescript recompose


    【解决方案1】:

    typing for compose is very generic 允许您指定结果组件的类型以及可以在 but it doesn't ensure the type safety or compatibility of the functions handed to it 上调用的组件类型。

    因此,最好避免使用compose 并简单地嵌套 HOC 调用:

    import { withProps } from 'recompose';
    
    import TestComponent from './TestComponent';
    
    export default withProps({
      foo: 'stringy string string',
    })(TestComponent);
    

    编辑:

    对于嵌套 HOC 而不是使用 compose 的添加代码示例,如下所示:

    export default setDisplayName('PlayerCardContainer')(
      withMutation(mutation)(
        withHandlers(createHandlers)(
          PlayerCard
        )
      )
    );
    

    【讨论】:

    • 不错的字符串值,顺便说一句?
    • 别担心,要记住的重要一点是setDisplayName('PlayerCardContainer')withMutation(mutation)withHandlers(createHandlers) 都返回函数compose 只是在调用下一个的结果上调用每个的语法糖。它将嵌套函数调用变成了一个漂亮的平面列表,但仅此而已。如果类型改进,保留语法糖会很好,但在类型改进之前,嵌套函数会更安全,因此 TypeScript 可以准确地知道发生了什么并可以有效地强制执行静态类型。
    • 啊哈,它刚刚为我正确点击了,非常感谢!
    • 嗯。 typing for setDisplayName uses a type argument。我可能会打开一个拉取请求来更改它,setDisplayName 没有理由无法推断类型。与此同时,您可以将{bar: string} 作为类型参数传递,如下所示:setDisplayName&lt;{bar: string}&gt;(...
    • 更新:PR just merged,因此您可以使用 @types/recompose 的 0.27.0 或更高版本删除 setDisplayName 的类型参数
    猜你喜欢
    • 2019-01-31
    • 2021-07-16
    • 2019-01-07
    • 2020-10-29
    • 2019-10-28
    • 2019-05-30
    • 2021-06-18
    • 2017-08-09
    相关资源
    最近更新 更多