简体   繁体   English

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

[英]Wildcard in React-Router 4 basename

In React-Router 4 I am configuring the basename like so: 在React-Router 4中,我像这样配置basename

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

Where * can be any integer. 其中*可以是任何整数。 However this isn't working - is my syntax wrong? 但是,这不起作用-我的语法错误吗?

You can create an array or something that allows you to dynamically create the link and route elements: 您可以创建一个数组或一些可以动态创建链接和路由元素的东西:

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

Here's a live sample of this approach: 这是此方法的实时示例:

https://codesandbox.io/s/vyO05x2g https://codesandbox.io/s/vyO05x2g

Also React Router offers using a colon inside the Route element. 此外,React Router还提供了在Route元素内使用冒号的功能。 Although this approach will render the same base component and in that one you should create your logic to render the specific data for that particular path: 尽管此方法将呈现相同的基本组件,但您应该在其中创建逻辑以呈现该特定路径的特定数据:

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

EDIT 编辑

Based on the comment, we weren't on the same page. 根据评论,我们不在同一页面上。 I'm assuming that you want to pass a different value depending on what your code does. 我假设您要根据代码的用途传递不同的值。 In that case you can use template literals to pass a variable, prop or state property to the base router: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals 在这种情况下,您可以使用模板文字将变量,属性或状态属性传递给基本路由器: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Like this: 像这样:

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

That should pass whatever wildcard is on each render of the component that has the <BrowserRouter /> on it. 那应该传递带有<BrowserRouter />的组件的每个渲染器上的wildcard

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM