我有一些使用React.createClass创建的组件的React代码。
某些组件将对象存储为对象作为常规属性,例如this.foo
而不是this.props.foo
或this.state.foo
。
有没有办法提供关于'foo'属性的Flow的提示?我现在想避免重写这些组件。
答案 0 :(得分:1)
您可以为传递给createClass
的对象提供显式类型。像
/* @flow */
import React from 'react';
type Spec = { foo: string };
const spec: Spec = {
foo: 'bar',
render() {
return <div>{this.foo}</div>;
}
}
const MyComponent = React.createClass(spec);
或者如果您希望保持内联类型,只需使用强制转换
/* @flow */
import React from 'react';
const MyComponent = React.createClass(({
foo: 'bar',
render() {
return <div>{this.foo}</div>;
}
}: { foo: string }));
要证明这一点,请尝试将foo
设为42
。 Flow会抱怨
/* @flow */
import React from 'react';
const MyComponent = React.createClass(({
foo: 42, // <-- error: number. This type is incompatible with string
render() {
return <div>{this.foo}</div>;
}
}: { foo: string }));