簡體   English   中英

React-Router 4基本名稱中的通配符

[英]Wildcard in React-Router 4 basename

在React-Router 4中,我像這樣配置basename

<BrowserRouter basename="/aaaa/bbbb/*/cccc">

其中*可以是任何整數。 但是,這不起作用-我的語法錯誤嗎?

您可以創建一個數組或一些可以動態創建鏈接和路由元素的東西:

// create the array with the ids and the components
const wildcards = [
  {id: 0, target: ComponentOne},
  {id: 1, target: ComponentTwo},
  {id: 2, target: ComponentThree}
];

// now map to create the links
{wildcards.map( e => {
  return <Link className="btn btn-secondary" to={`/aaa/bbb/${e.id}/ccc`}>Component {e.id}</Link>
})}

// then the routes
{ wildcards.map( e => {
  return <Route path={`/aaa/bbb/${e.id}/ccc`} component={e.target} key={`component_${e.id}`}></Route>
})}

這是此方法的實時示例:

https://codesandbox.io/s/vyO05x2g

此外,React Router還提供了在Route元素內使用冒號的功能。 盡管此方法將呈現相同的基本組件,但您應該在其中創建邏輯以呈現該特定路徑的特定數據:

<Route path="/aaa/bbb/:id/ccc" component={MyBaseComponent}></Route>

// then in the base component
const MyBaseComponent = ({match}) => {
  // run your logic here
  return(
    <div>Your content depending on the match params</div>
  );
};

編輯

根據評論,我們不在同一頁面上。 我假設您要根據代碼的用途傳遞不同的值。 在這種情況下,您可以使用模板文字將變量,屬性或狀態屬性傳遞給基本路由器: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

像這樣:

<BrowserRouter basename=`/aaaa/bbbb/${wildcard}/cccc`>

那應該傳遞帶有<BrowserRouter />的組件的每個渲染器上的wildcard

暫無
暫無

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

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