【问题标题】:React TypeScript how to bind array to routes?React TypeScript 如何将数组绑定到路由?
【发布时间】:2018-04-08 02:22:40
【问题描述】:

我使用标准的 VisualStudio 2017 ASP.NET Core 2.0 React 模板。 我有来自模板的课程Home

import { RouteComponentProps } from 'react-router';

export class Home extends React.Component<RouteComponentProps<{}>, {}> {
    public render() {
        return <div>
            <h1>Hello, world!</h1>
        </div>;
    }
}

我需要创建routesData 数组并将Home 之类的组件绑定到“布局”路由。这是我的尝试代码:

interface RouteDataItem {
    path: string;
    exact: boolean;
    main: () => Element;
}

export const routesData = [
    {
        path: '/',
        exact: true,
        main: () => <Home />
    },
    {
        path: '/counter',
        main: () => <Counter />
    },
    {
        path: '/fetchdata',
        main: () => <FetchData />
    }
]

export const routes = <Layout>
    {routesData.map((route, index) => {
        return <Route exact={route.exact} key={index} path={route.path} component={route.main} />;
    }}
</Layout>;

我该怎么做? VisualStudio 显示错误Property "match" is absent in type "{}" 在这条线上

main: () => <Home />

&lt;Home /&gt; 是红色下划线。

【问题讨论】:

    标签: reactjs typescript react-router


    【解决方案1】:

    您应该在&lt;home /&gt; 中添加RouteComponentProps 的属性,因为您的主组件使用RouteComponentProps 作为其属性

    如果您在 Visual Studio 中按 ctrl+单击 RouteComponentProps,您可以查看有关 RouteComponentProps 属性的更多信息

    【讨论】:

    • 好的。我明白。 main: (???) =&gt; &lt;Home RouteComponentProps={???} /&gt; 但是在标记为??? 的地方写什么。
    • 工作:main: (match: match&lt;any&gt;, location: H.Location, history: H.History) =&gt; &lt;Home match={match} location={location} history={history} /&gt; import * as H from 'history';
    【解决方案2】:

    Typescript 无需在函数内部传递即可识别 react.fc 类型。

    你只需要传递组件名称,例如:

    export const Home:React.FC = () => (
    <Layout
      footer={false}
    >
      Exampĺe
    </Layout>
    )
    

    并在路由中传递组件

    import React from 'react'
    import Home from './Home/Home'
    
    interface RouteDataItem {
        path?: string;
        name?: string;
        isProtected?: boolean;
        component?: React.FC;
    }
    
     export const routes: RouteDataItem[] = [
      {
        path: '/',
        name: 'Feed',
        isProtected: true,
        component: Home
      }
    
    ]
    

    和路由..

    {routes.map((route) => (
              // eslint-disable-next-line react/jsx-key
              <Route path="/" exact={true} component={route.component} />
            ))}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-22
      • 1970-01-01
      • 1970-01-01
      • 2018-04-27
      • 2021-01-31
      • 2014-01-15
      • 2018-01-18
      • 2023-02-07
      相关资源
      最近更新 更多