【发布时间】:2016-06-03 03:50:28
【问题描述】:
为了设置上下文,我在 lesson 12 of react-router-tutorial,但随着我的跟进,我实际上是在 TypeScript 中做所有事情。在教程的这一点上,在几个 React 组件中,有一个叫做 Repos
export class Repos extends React.Component<ReposProps, {}> { ... }
这是在Router 中创建的
<Router history={browserHistory}>
{/* ... */}
<Route path="/repos" component={Repos}>{/* ... */}</Route>
{/* ... */}
</Router>
Repos 中的某处是一种方法,它从 HTML 表单中获取一些参数并构造一条新路径以将浏览器定向到:
handleSubmit(event: React.FormEvent) {
/* ... (define userName and repo vars) */
const path = `/repos/${userName}/${repo}`
this.context.router.push(path);
}
我的问题是最后一行的context 和router 的类型是什么?
在the React documentation on Contexts 中,我了解到上下文通常在每个元素中定义。这里似乎一个绝妙的主意是在Repos 中定义context,其接口扩展自react-router's TypeScript type definitions 中定义的某个接口
interface ReposContext extends Something /* ??? */ { }
在这里,Something 会将router 定义为具有push 方法的某种类型。
API 并没有说 Router 有一个方法 push 虽然 Glossary 有,这令人困惑。无论如何,DefinitelyTyped 上的类型定义并没有在 Router 下定义 push 方法(虽然我不相信它们是完美的,但这种遗漏对我来说似乎不是偶然的)
同样的 API 确实指出了 RouterContext,其中提到了 context.router -- context.router 确实定义了 push() 以及许多其他方法。
然后我注意到在 react-router 的类型定义的 history.d.ts 中,接口 History 具有所有相同的方法(加上更多
也许这个界面正在接近。它没有像我想要的那样扩展任何东西(也许这是 react-router 类型改进的空间),但它有我需要的东西。
interface ContextRouter extends History { }
interface ReposContext {
router: ContextRouter
}
我仍然持怀疑态度,因为尽管 ContextRouter 扩展了 History 并不完全有意义
【问题讨论】:
标签: reactjs typescript react-router