在 react-router 中,this.context.router 的类型是什么?

3
为了让大家了解背景,我在 react-router-tutorial中的第12课。但是由于我在跟随教程时使用的是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);
}

我的问题是,最后一行的contextrouter的类型是什么?

React文档中关于Context中提到,通常在每个元素中定义context。在这里,一个聪明的想法似乎是在Repos中定义context,并使用一个接口来扩展react-router的TypeScript类型定义中定义的某个接口。

interface ReposContext extends Something /* ??? */ { }

这里,Something 会被定义为某种类型,该类型具有 push 方法。

API 没有说明 Router 具有 push 方法,尽管 术语表 中有,这很令人困惑。无论如何,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,但它并不完全合理。

2个回答

2

我使用ReactRouter.RouterOnContext:

context: {
    router: ReactRouter.RouterOnContext
}

0

我通过深入研究react-router代码解决了这个问题。通过弄清楚路由器是如何创建的,我最终进入了match.js,在那里我发现路由器实际上是通过将history传递给createRouterObject来创建的,后者只是创建一个具有与history相同属性以及其他一些属性的对象。

路由器的类型确实扩展了History。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接