在React中,捕获(并将传递给组件的所有其他道具传递给组件的子组件)相当普遍(至少在我见过的代码库中)。我试图用流类型来表达这种关系(也就是说,父组件应该接受子组件的所有道具,除了那些显式传递给渲染子对象的道具)。
我的最佳尝试示例有望对此有所澄清(also on flow.org/try):
// @flow
import React, { Component } from 'react';
type AProps = {
foo: string,
bar: number,
}
class A extends Component<AProps> {
render() {
return null;
}
}
type BProps<T> = {
baz: number,
} & T;
class B<T: {}> extends Component<BProps<T>> {
render() {
const { baz, ...rest: T } = this.props;
return <A foo="hello" {...rest} />;
}
}
// $ExpectError
<B baz={3} />
A 是需要两个道具 foo 和 bar 的组件; B 是采用道具 baz 的组件,但还将任何其他组件传递给正在渲染的 A 。渲染 A 时,我们还明确传递了foo="hello"
。
我的目的是键入 B ,以便可以使用 baz 道具,加上根据AProps
的任何其他道具,减去< em> foo 道具,因为它在呈现 A 时已显式传递。本质上,从流已经知道 A 的上下文中,我希望将T
推断为$Diff<AProps, { foo: string }>
,并且最好不必明确提及AProps
。 strong>以及渲染 A 和 B 时使用的道具。
我也不太确定为什么要进行上述类型检查(我希望/希望在渲染<B baz={3} />
时出错,因为没有传入 bar 道具,所以它也不会传递给 A 。
如何键入 B ,这样它实际上将以Component<{ bar: number, baz: number }>
结尾,而无需显式引用AProps
,而不必复制有关我们明确传递的道具的信息到 A 上?