React-Router 4 basename 中的通配符 [英] Wildcard in React-Router 4 basename

查看:17
本文介绍了React-Router 4 basename 中的通配符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 React-Router 4 中,我像这样配置 basename:

In React-Router 4 I am configuring the basename like so:

<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

React Router 还提供在 Route 元素内使用冒号.尽管这种方法将呈现相同的基本组件,但您应该在其中创建逻辑来呈现该特定路径的特定数据:

Also React Router offers using a colon inside the Route element. 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>
  );
};

<小时>

编辑

根据评论,我们不在同一页面上.我假设您想根据代码的作用传递不同的值.在这种情况下,您可以使用模板文字将变量、道具或状态属性传递给基本路由器:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

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

像这样:

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

这应该传递在其上具有 的组件的每个渲染上的任何 wildcard.

That should pass whatever wildcard is on each render of the component that has the <BrowserRouter /> on it.

这篇关于React-Router 4 basename 中的通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆