要设置上下文,我在 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
中使用从 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/