【发布时间】:2018-08-09 14:14:57
【问题描述】:
我正在尝试验证 React 组件在调度新的屏幕操作时是否接收到正确的属性。
路线可能如下所示。
class MyCompAB extends React.Component<{a: number, b: string}> {}
class MyCompCD extends React.Component<{c: number, d: string}> {}
const myRoutes = {'/ab': MyCompAB, '/cd': MyCompCD};
我需要的是这样的东西。我只是还没有找到方法让 openScreen 验证 props 是否适用于路线 [name]。
type Screen<P> = ComponentType<P>;
type Routes<P> = {[key: string]: Screen<P>};
function openScreen<P, R: Routes<mixed>, K: $Keys<R>>(routes: R, name: K, props: P): void {
// This needs to validate that props are valid for the component in routes[name].
// This won't do <Component {...props} />. Instead redux dispatch magic happens here.
type Pepe = $Call<R<P>, K>;
}
// $ExpectError. Should fail: a and b missing.
openScreen(myRoutes, '/ab', {});
// $ExpectError. Should fail: b has wrong type.
openScreen(myRoutes, '/ab', {a: 1, b: 1});
// Should work.
openScreen(myRoutes, '/ab', {a: 1, b: "1"});
// $ExpectError. Should fail: c and d missing.
openScreen(myRoutes, '/cd', {});
// $ExpectError. Should fail: d has wrong type.
openScreen(myRoutes, '/cd', {c: 1, d: 1});
// Should work.
openScreen(myRoutes, '/cd', {c: 1, d: "1"});
我该如何进行这项工作?
【问题讨论】:
标签: reactjs react-native react-navigation flowtype