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

标签 reactjs typescript react-router

要设置上下文,我在 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);
}

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

the React documentation on Contexts我开始明白上下文通常在每个元素中定义。在 Repos 中使用从 react-router's TypeScript type definitions 中定义的某个接口(interface)扩展的接口(interface)来定义 context 似乎是一个绝妙的主意。

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 中,接口(interface) History 具有所有相同的方法(加上更多

也许这个界面会越来越接近。它没有像我想要的那样扩展任何东西(也许这是 react 路由器类型改进的空间),但它有我需要的东西。

interface ContextRouter extends History { }

interface ReposContext {
    router: ContextRouter
}

我仍然持怀疑态度,因为尽管 ContextRouter 扩展了 History

但它并没有多大意义

最佳答案

我使用 ReactRouter.RouterOnContext:

context: {
    router: ReactRouter.RouterOnContext
}

关于reactjs - 在react-router中,this.context.router的类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35541455/

相关文章:

Javascript 代码可读性 - 是否拆分成更小的函数?

javascript - 如何在reactJS中输入def?

javascript - 如何查看 Vite 项目中的公共(public)目录进行热重载?

javascript - react 日期选择器过滤日期问题

javascript - React Router v4 基于参数获取数据

reactjs - 尝试使用 ConnectedRouter 进行与推送一起使用的重定向,我的 redux mapStateToProps 给出错误

reactjs - React-Router 在新选项卡中打开链接

javascript - 无法读取我的 API 或特定 API [React.js/Node.js/Axios/Fetch]

javascript - Typescript 接口(interface)未捕获类型错误 : Cannot set property

angular - 我如何在 Angular 6 中以人类可读的方式表示文件大小?