gpt4 book ai didi

reactjs - 流量: How to type a HOC that accepts a prop the wrapped component doesn't care about

转载 作者:行者123 更新时间:2023-12-02 03:45:47 25 4
gpt4 key购买 nike

我不太确定如何在 Flow 0.57.3 中输入以下 HOC:

// @flow
import React, {Component, type ComponentType} from 'react';

type OwnProps = {
onFoo: void => void
};

// What we want from the returned wrapper component:
// - enforces presence of `onFoo` prop
// - enforces the prop contract of the passed-in WrappedComponent
function WithOnFoo<Props: {}>(
WrappedComponent: ComponentType<Props>
): ComponentType<Props & OwnProps> {
return class WithOnFoo extends Component<Props & OwnProps> {
componentDidMount() {
this.props.onFoo();
}

render() {
return <WrappedComponent {...this.props} />;
}
};
}

const MyComponent = ({name}: {name: string}) => (
<p>Hi, {name}</p>
);

const wrapped = WithOnFoo(MyComponent);

尝试一下 here .

该评论解释了我正在寻找的内容:返回的包装器组件

  • 强制存在 onFoo 属性
  • 强制传入的 WrappedComponent 的 prop 契约

Flow 提示说:

20:             return <WrappedComponent {...this.props} />;
^ props of React element `WrappedComponent`. This type is incompatible with
11: function WithOnFoo<Props: {}>( ^ some incompatible instantiation of `Props`

我不太确定这个错误在提示什么。我知道我不会费尽心思将 HOC 的 onFoo 属性传递给 WrappedComponent,但我不确定这就是问题的根源。

有什么想法吗?

最佳答案

同时<Props: {}>允许this.props为了传播,我们知道onFoo应该是要包装的组件的 Props 的一部分。所以我们应该声明传递给WithOnFoo的组件的props有 onFoo ,即

function withOnFoo<Props: {} & OwnProps>(
WrappedComponent: ComponentType<Props>
): ComponentType<Props> {
// implementation here ...
}

另请注意 PropsWithOnFoo 的实现细节中的“一流”类型(其中会有 onFoo)。所以你可以替换你写的Props & OwnProps的地方与 Props .

参见the flow example here

注意:我修改了一些术语来帮助自己理解您的示例

WithOnFoo变成callsOnFooOnComponentDidMount

OwnProps变成RequiredProps

关于reactjs - 流量: How to type a HOC that accepts a prop the wrapped component doesn't care about,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46818264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com