簡體   English   中英

使用 react-router-dom 在 Route 中添加一個組件作為 props

[英]Add a component as props inside a Route with react-router-dom

具有以下代碼:

import { Switch, Route, BrowserRouter as Router } from 'react-router-dom';

export function MyComponent({ list }: MyComponentProps) {
  return (
    <Router>
      <Switch>
        <Route path={list[0].url} component={<NextComponent />} />
      </Switch>
    </Router>
  );
}

我想在該路線上加載不同的組件。

react-router-dom是 5.2.0。

此代碼不起作用,它在<Route path...下出現一條紅線<Route path...說明:

Operator '<' cannot be applied to types 'number' and 'typeof Route'.ts(2365)
(alias) class Route<T extends {} = {}, Path extends string = string>
import Route

有任何想法嗎?

react-router-dom v5 中,您沒有將component prop 指定為 JSX 文字(RRDv6 語法),只需傳遞對組件的引用。

component={NextComponent}而不是component={<NextComponent />}

代碼

export function MyComponent({ list }: MyComponentProps) {
  return (
    <Router>
      <Switch>
        <Route path={list[0].url} component={NextComponent} />
      </Switch>
    </Router>
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM