如何将 navigationOptions 添加到记忆化的反应功能组件?

How to add navigationOptions to a memoized react functional component?

我正在使用流程类型并且有一个备忘录包装的功能组件,但是当尝试为反应导航分配导航选项时,流程变得混乱:

在我的组件上

const navigationOptions = ({navigation}) => ({}) // more stuff

const Foo = memo((props: IProps) => {
...
})

/*
Here it breaks down
Cannot assign `navigationOptions` to `Foo['navigation...']` because property `navigationOptions` is missing in  `React.AbstractComponentStatics`
*/
Foo.navigationOptions = navigationOptions
export default Foo

即使我将它转换为任何类型,然后尝试在我的路由器上使用它:

/*
Cannot call `createStackNavigator` with object literal bound to `routeConfigMap` because in property `Foo.screen`: Either property `navigationOptions` is missing in  AbstractComponent [1] but exists in  `withOptionalNavigationOptions` [2]. Or property `router` is missing in  AbstractComponent [1] but exists in  `withRouter` [3].Flow(InferError)
*/
const FooStack = createStackNavigator({
  Foo: { screen: FooScreen }
}, stackNavOptions)

我应该如何在此处正确应用类型?

这是预期的行为。如果您实际检查 React$AbstractComponentStatics,您会发现允许的属性非常少,例如 displayName 是有效的。他们甚至删除了 propTypes,尽管它是有效的,但不被鼓励,这就是它被删除的原因。

要解决这个问题,您可以使用抑制评论将其标记为误报,

// $FlowExpectedError navigationOptions
Foo.navigationOptions = navigationOptions

Flow 支持 $FlowFixMe 并且从版本 0.125.0 开始,$FlowIssue$FlowExpectedError 默认情况下会抑制错误。