以下代码可用于注释通过prop的HOC
/* @flow */
import * as React from 'react';
/* withHoverState HOC */
type State = {
hover: boolean,
};
export type InjectedProps = {|
foo: string
|};
function withHoverState<T>(
InnerComponent: React.ComponentType<{| ...T, ...InjectedProps |}>
): React.AbstractComponent<T> {
return (props) => <InnerComponent {...props} foo="bar" />
};
/* Button HOC */
type ButtonProps = {|
text: string,
...InjectedProps
|}
const UnwrappedButton = ({ text, foo }: ButtonProps) => <button>${text} - ${foo}</button>
const Button = withHoverState(UnwrappedButton);
/* Test usage */
const Test1 = () => <Button text="test" />
但是,我需要将内部组件作为一个类,并且当我对其进行更改时,流程将不再令人满意
/* @flow */
import * as React from 'react';
/* withHoverState HOC */
type State = {
hover: boolean,
};
export type InjectedProps = {|
foo: string
|};
function withHoverState<T>(
InnerComponent: React.ComponentType<{| ...T, ...InjectedProps |}>
): React.AbstractComponent<T> {
class Inner extends React.Component<T> {
render() {
return (
<InnerComponent
foo="bar"
{...this.props}
/>
);
}
};
return Inner;
}
/* Button HOC */
type ButtonProps = {|
text: string,
...InjectedProps
|}
const UnwrappedButton = ({ text, foo }: ButtonProps) => <button>${text} - ${foo}</button>
const Button = withHoverState(UnwrappedButton);
/* Test usage */
const Test1 = () => <Button text="test" />
给出错误
29: return Inner;
^ Cannot return `Inner` because inexact class `Inner` [1] is incompatible with exact `T` [2].
References:
19: class Inner extends React.Component<T> {
^ [1]
[LIB] ..//static/v0.122.0/flowlib/react.js:258: > = React$AbstractComponent<Config, Instance>;
谁能告诉我如何使注释与类组件一起工作?