【问题标题】:Wildcard in React-Router 4 basenameReact-Router 4 基本名称中的通配符
【发布时间】:2017-07-26 10:15:00
【问题描述】:

在 React-Router 4 中,我正在配置 basename,如下所示:

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

其中* 可以是任何整数。但是这不起作用 - 我的语法错了吗?

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    您可以创建一个数组或其他允许您动态创建链接和路由元素的东西:

    // 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`>
    

    这应该传递带有&lt;BrowserRouter /&gt; 的组件的每个渲染上的任何wildcard

    【讨论】:

    • 谢谢 - 但我的问题是我是否可以在 basename 属性中使用通配符。
    • 我相信您可以通过匹配括号 () 中更改的字符串部分并使用正则表达式来使用通配符,即“aaaa/bbbb/(*)/cccc”
    猜你喜欢
    • 2023-04-03
    • 2017-06-30
    • 2017-05-17
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    相关资源
    最近更新 更多