gpt4 book ai didi

reactjs - 如何使用 Typescript 将组件传递到 react 路由器路由中?

转载 作者:搜寻专家 更新时间:2023-10-30 21:12:33 25 4
gpt4 key购买 nike

当我将一些组件传递给 Route 组件时,出现 TS 编译器错误:

Type '{ main: typeof MainComponent; sidebar: typeof SidebarComponent; }' is not assignable to type 'RouteComponents'. Property 'sidebar' is incompatible with index signature. Type 'typeof SidebarComponent' is not assignable to type 'ReactType'. Type 'typeof SidebarComponent' is not assignable to type 'StatelessComponent'. Type 'typeof SidebarComponent' provides no match for the signature '(props: any, context?: any): ReactElement'

我试图正确构造一个 RouteComponents 对象,但我不得不修改 react-routerindex.d.ts 导出 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}部分没有报错,但是创建indexRouteComponents对象报错(和上面一样报错,因为不是正确的RouteComponents 对象)

使用 Typescript 设置 react-router 组件的正确方法是什么?

编辑:以下是与此相关的 Github 问题: https://github.com/ReactTraining/react-router/issues/4317 https://github.com/DefinitelyTyped/DefinitelyTyped/issues/13689

最佳答案

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>
)
}

关于reactjs - 如何使用 Typescript 将组件传递到 react 路由器路由中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41421165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com