如何使用flowtype在组件的反应上下文中定义prop?

loc*_*ton 7 javascript reactjs flowtype

使用flowtype以这种方式在上下文中定义prop

// @flow
type MyType = Object;
class CustomView extends React.Component {
    static childContextTypes = {
        someProp: MyType
    }
    getChildContext() {
        return {
            someProp: this.props.someProp
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

CustomView:子上下文的类型规范someProps无效; 类型检查器函数必须返回nullError 返回一个对象.您可能忘记将参数传递给类型检查器创建器(arrayOf,instanceOf,objectOf,oneOf,oneOfType和shape都需要参数).

所以我被迫使用propTypes.object而不是Object.

Jes*_*ett 4

不,您不能将 Flow 类型用作 中的类型childContextTypes。原因是它childContextTypes是在运行时检查的,而 Flow 类型没有任何运行时表示。因此,其中的“类型”必须是值 - 特别是prop-typeschildContextTypes npm 包提供的值。

在您的示例中使用MyType实际上是一个语法错误:MyType出现在对象属性值的位置,该属性值必须是值,而不是类型。