当我将一些组件传递给Route
组件时,我得到一个TS编译器错误:
输入'{main:typeof MainComponent;侧栏:typeof SidebarComponent; }'不能赋值为'RouteComponents'。 属性“侧边栏”与索引签名不兼容。 类型'typeof SidebarComponent'不能分配给'ReactType'类型。 类型'typeof SidebarComponent'不能分配给'StatelessComponent'类型。 类型'typeof SidebarComponent'不提供签名'匹配'(props:any,context?:any):ReactElement'
我尝试正确构建RouteComponents
对象,但我必须修改react-router
的{{1}}以将index.d.ts
定义导出为{{1}导出,它仍然不喜欢表达式。我在哪里可以找到RouteComponents
对象看起来像什么?
以下是简单文件RouteComponent
:
RouteComponents
正如我所提到的,我也尝试过以下方式:
routes.tsx
import * as React from 'react'
import { IndexRoute, Route } from 'react-router'
import App from './components/App'
import MainComponent from './components/MainComponent'
import OtherMainComponent from './components/OtherMainComponent'
import SidebarComponent from './components/SidebarComponent'
const routes = () => {
return (
<Route path="/" component={App}>
<IndexRoute components={{ main: MainComponent, sidebar: SidebarComponent }} />
<Route path="/add" components={{ main: OtherMainComponent, sidebar: SidebarComponent }} />
</Route>
)
}
export default routes
部分没有错误,但是创建const indexRouteComponents: RouteComponents = {
main: MainComponent,
sidebar: SidebarComponent
}
const routes = () => {
return (
<Route path="/" component={App}>
<IndexRoute components={indexRouteComponents} />
<Route path="/add" components={{ main: OtherMainComponent, sidebar: SidebarComponent }} />
</Route>
)
}
对象是一个错误(与上面相同的错误,因为它不是正确的components={indexRouteComponents}
对象)
使用Typescript设置indexRouteComponents
组件的正确方法是什么?
编辑:这是与此相关的Github问题: https://github.com/ReactTraining/react-router/issues/4317 https://github.com/DefinitelyTyped/DefinitelyTyped/issues/13689
答案 0 :(得分:1)
const AppRouter = [
{
main: MainComponent,
exact: true,
path: "/",
sidebar: SidebarComponent,
},
{
main: OtherMainComponent,
exact: true,
path: "/add",
sidebar: SidebarComponent,
}
];
在您的主要组件中:
public render() {
return (
<Router>
<div className={"sidebar"}>
{AppRouter.map((route, index) => (
<Route
key={index}
path={route.path}
exact={route.exact}
component={route.sidebar}
/>
))}
</div>
<div className={"content"}>
{AppRouter.map((route, index) => (
<Route
key={index}
path={route.path}
exact={route.exact}
component={route.main}
/>
))}
</div>
</Router>
)
}