如何在 React.CreateClass 中为对象属性提供流类型提示
How to provide flowtype hints in React.CreateClass for object properties
我有一些使用 React.createClass 创建的组件的 React 代码。
一些组件将对象上的东西存储为普通属性,例如this.foo
与 this.props.foo
或 this.state.foo
相对。
有什么方法可以向 Flow 提供关于 'foo' 属性 的提示吗?我想暂时避免重写这些组件。
您可以为传递给 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 */
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 }));
我有一些使用 React.createClass 创建的组件的 React 代码。
一些组件将对象上的东西存储为普通属性,例如this.foo
与 this.props.foo
或 this.state.foo
相对。
有什么方法可以向 Flow 提供关于 'foo' 属性 的提示吗?我想暂时避免重写这些组件。
您可以为传递给 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 */
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 }));