例如:
import { withProps } from 'recompose'
type Props = {
name: string,
};
const NameTag = ({ name }: Props) => (
<p style={{color: 'pink'}}>
{ name }
</p>
);
const MyNameTag = withProps({
// i want a error here
name: 1
})(NameTag);
如何获得无法将数字1
传递给NameTag组件的道具name
的错误?
谢谢。
答案 0 :(得分:1)
使用HOC时,至少Flow 0.78会给您一个错误。
因此,如果您在代码上添加<MyNameTag />
,它应该会为您提供。
string [1] is incompatible with number [2] in property name of the first argument.
[1] 7│ name: string,
8│ };
9│
10│ const NameTag = ({ name }: Props) => (
11│ <p style={{color: 'pink'}}>
12│ { name }
13│ </p>
:
[2] 19│ name: 1
之所以会发生这种情况,是因为您在实例化name
时仍然可以通过NameTag
,直到现在还不清楚它是否会失败。
流程是如此复杂,而我的流程却很薄弱,所以我不敢说这是一个流程错误。
到目前为止,我发现捕获声明错误的唯一方法是构建一个HOC,该HOC仅允许未被覆盖的属性,而没有其他任何属性。您将需要声明具有严格属性{| a: string |}
的组件。检查此示例:
// @flow
import * as React from 'react'
function myWithProps<
MP, // My Properties. These are the pre-entered properties.
CP, // Component properties. The properties originally expected by
// the component.
C: React.ComponentType<CP>, // The original component itself. Used to
// extract the properties template CP.
IP: $Diff<CP, MP>, // Input properties. Properties that must be received
// by the HOC. We only expect the properties of the
// original component CP minus the properties MP that
// were specified when we created the HOC.
>(myProps: MP): C => React.ComponentType<IP> {
return component => props => <component {...myProps} {...props} />;
}
type Props = {|
name: string,
age: number,
|};
const NameTag = ({ name, age }: Props) => (
<p style={{color: 'pink'}}>
{ name } { age }
</p>
);
// $ExpectError. name has a wrong type.
const MyNameTag = myWithProps({name: 1})(NameTag);
// Should work.
const MyOtherNameTag = myWithProps({name: "hello"})(NameTag);
// Should work.
<MyOtherNameTag age={21} />;
// $ExpectError. name cannot be overriden.
<MyOtherNameTag age={21} name={"John"} />;
// $ExpectError. age has a wrong type.
<MyOtherNameTag age={"21"} />;
// $ExpectError. age missing.
<MyOtherNameTag />;
// $ExpectError. Unexpected parameter.
<MyOtherNameTag age={21} nmae={"John"} />;
myWithProps使用泛型类型,因此它可以与任何类一起使用。
我希望这会有所帮助!