在 React 路由器 5 中使用变量(不是静态组件)将道具传递给组件

Posted

技术标签:

【中文标题】在 React 路由器 5 中使用变量(不是静态组件)将道具传递给组件【英文标题】:Passing props to a component using a variable (not a static component) in React router 5 【发布时间】:2021-12-06 21:33:03 【问题描述】:

我知道在 react-router 5 中,您可以像这样将一些道具传递给子组件:

<Route path="/"    
   exact
   render= props => <MyPage title=myTitle dataPath=myDataPath 
   ...props /> />

但就我而言,我使用的是路线模型:

import  ComponentType, FC  from "react";

interface RouteItem 
  key: string;
  title: string;
  tooltip?: string;
  path?: string;
  component?: FC<>;
  contentPath?: string;
  enabled: boolean;
  icon?: ComponentType;
  subRoutes?: Array<RouteItem>;
  appendDivider?: boolean;


export default RouteItem;

然后我在配置文件 (config/index.ts) 中定义这些,如下所示:

// components
import DetailPageTemplate from "../pages/DetailPageTemplate";

// interface
import RouteItem from '../model/RouteItem.model';

// define app routes
export const routes: Array<RouteItem> = [
  
    key: "router-detail-one",
    title: "Detail One",
    path: "/detail-one",
    enabled: true,
    contentPath: '../data/DetailOneCopy.json',
    component: DetailPageTemplate,
    appendDivider: true,
  ,
  
    key: "router-detail-two",
    title: "Detail Two",
    path: "/detail-two",
    enabled: true,
    contentPath: '../data/DetailTwoCopy.json',
    component: DetailPageTemplate,
    appendDivider: true,
  ,
];

这感觉像是一个非常愚蠢的问题(我对语法不熟悉)但我希望能够在我的 App.tsx 内的循环中传递其中一些参数,但我不知道如何将道具传递给组件变量(因为它不是 JSX):

import React from 'react';

// components
import Layout from './components/global/Layout';
import  BrowserRouter as Router, Switch, Route  from 'react-router-dom';

// app routes
import  routes  from './config';

// interfaces
import RouteItem from './model/RouteItem.model';

// define app context
const AppContext = React.createContext(null);

// default component
const DefaultComponent = () => <div>No Component Defined.</div>;

function App() 
  // const [useDefaultTheme, toggle] = useReduc

  return (
    <>
      <AppContext.Provider value=null>
          <Router>
            <Switch>
              <Layout>
                routes.map((route: RouteItem) =>
                  (
                    <Route
                      key=`$route.key`
                      path=`$route.path`
                      component=route.component || DefaultComponent
                       /*       ^ How can I pass props to the component? */ 
                      exact
                    />
                  )
                )
              </Layout>
            </Switch>
          </Router>
        </ThemeProvider>
      </AppContext.Provider>
    </>
  );


export default App;

【问题讨论】:

【参考方案1】:

我认为您可以将 route.component 用作 JSX &lt;route.component /&gt; 但为了命名一致性(大写),您可以先将其分配给 const

              routes.map((route: RouteItem) => 
                const Component = route.component;
                return (
                  <Route
                    key=`$route.key`
                    path=`$route.path`
                    component=
                      (Component &&
                        ((props: any) => <Component ...props />)) ||
                      DefaultComponent
                    
                    exact
                  />
                );
              )

https://codesandbox.io/s/react-router-dom-typescript-dynamic-component-s7n72?file=/src/index.tsx

【讨论】:

感谢您的回答,终于有机会看看这个。我认为这会起作用,但我可能还需要更新模型——因为这是一种 FC 类型,打字稿用 Type '( title, contentPath : title: any; contentPath: any; ) =&gt; ReactElement&lt;any, string | JSXElementConstructor&lt;any&gt;&gt;' is not assignable to type 'FunctionComponent&lt;&gt;'. Types of parameters '__0' and 'props' are incompatible. Type ' children?: ReactNode; ' is missing the following properties from type ' title: any; contentPath: any; ': title, contentPath TS2322 向我抱怨 @brandonscript 你可以尝试将component?: FC&lt;&gt;; 更改为component: React.ReactElement 这是组件prop 的类型 @brandonscript nvm,我看错了类型,试试这个component?: React.ComponentType&lt;any&gt;,和DefinitelyTyped中的类型一样 Hrm,这也不起作用,但是由于您从技术上回答了我最初的问题,所以无论如何我都会将其标记为已接受!感谢您的帮助。 @brandonscript 好的,不管怎样,我会在晚上再看看

以上是关于在 React 路由器 5 中使用变量(不是静态组件)将道具传递给组件的主要内容,如果未能解决你的问题,请参考以下文章

在使用react构建的网站中提供另一个(独立)页面或静态文件

在使用 react 构建的网站中提供另一个(独立)页面或静态文件

React 更改静态文件的默认路由

ReactJS- 在带有 React 路由器的 URL 中使用 slug 而不是 Id

Linux之网络管理静态路由小案例

react中如何在静态方法中调用静态属性