简体   繁体   English

HOC类型可以通过自身的特性来增强组件吗?

[英]Type HOC that enhances component with its own properties?

I'm trying to type an Higher Order Component (HOC) using Recompose and its HOC type, using Flow. 我正在尝试使用Recompose和它的HOC类型(使用Flow)键入一个高阶组件(HOC)。

This is my code: 这是我的代码:

// @flow
import React from 'react';
import { compose, defaultProps, withProps, type HOC } from 'recompose';

type InnerProps = {
  text: string,
  num: number,
};

type EnhancedComponentProps = {
  text: string,
};

const baseComponent = ({ text, num }: InnerProps) => (
  <div>
    {text}
    {num}
  </div>
);

const enhance: HOC<*, EnhancedComponentProps> = compose(
  defaultProps({
    text: 'world',
  }),
  withProps(({ text }) => ({
    text: `Hello ${text}`,
  }))
);

export default enhance(baseComponent);

Right now this fails with: 现在这失败了:

Cannot call enhance with baseComponent bound to a because property num is missing in object type [1] but exists in
InnerProps [2] in the first argument.

     src/Text.js
 [2] 14│ const baseComponent = ({ text, num }: InnerProps) => (
       :
     27│   }))
     28│ );
     29│
     30│ export default enhance(baseComponent);
     31│

     flow-typed/npm/recompose_v0.x.x.js
 [1] 95│   ): HOC<{ ...$Exact<Enhanced>, ...BaseAdd }, Enhanced>;

Trying to read the docs and some blog posts I couldn't reach to a solution. 试图阅读文档和一些博客文章,但我找不到解决方案。 All the examples I find are very trivial and none of them cover this simple case. 我发现的所有示例都很琐碎,没有一个涵盖这个简单的案例。

What's the right way to type this code? 键入此代码的正确方法是什么?

I guess you get the right error. 我猜你得到正确的错误。 It says: 它说:

num is missing in object type [1] but exists in InnerProps [2] in the first argument. 对象类型[1]中缺少num,但在第一个参数的InnerProps [2]中存在num。

You declared that your HOC will get what's in EnhancedComponentProps which is missing the num . 您声明了HOC将获得EnhancedComponentProps中缺少num In other words, you try to extract num from Object that will only get what's declared in EnhancedComponentProps type. 换句话说,您尝试从Object提取num ,而该num仅会获得EnhancedComponentProps类型中声明的内容。

Based on recompose docs: you should get this work by: 基于重组文档:您应通过以下方式获得此项工作:

// @flow
import React from 'react';
import { compose, defaultProps, withProps, type HOC } from 'recompose';

type EnhancedComponentProps = {
  text: string,
  num: number,
};

const baseComponent = ({ text, num }: EnhancedComponentProps) => ( // in the example from recompose this typing is unnecessary though
  <div>
    {text}
    {num}
  </div>
);

const enhance: HOC<*, EnhancedComponentProps> = compose(
  defaultProps({
    text: 'world',
  }),
  withProps(({ text }) => ({
    text: `Hello ${text}`,
  }))
);

export default enhance(baseComponent);

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

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