作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我不太确定如何在 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
属性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 ...
}
另请注意 Props
是 WithOnFoo
的实现细节中的“一流”类型(其中会有 onFoo)。所以你可以替换你写的Props & OwnProps
的地方与 Props
.
注意:我修改了一些术语来帮助自己理解您的示例
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/
我是一名优秀的程序员,十分优秀!