【问题标题】:How to get ":name" from "path"?如何从“路径”中获取“:名称”?
【发布时间】:2022-01-07 15:03:50
【问题描述】:

所以我有这个。 如何从“路径”中获取“:名称”作为参数并将其提供给 BlogPage 组件的字段“somefield”?

<Route 
   path = "/blog/:name" 
   element={
      <BlogPage
         {// how to do this?}
         somefield = ? 
      />
   }
/>

【问题讨论】:

  • 我用“window.location.href”解决了这个问题

标签: reactjs react-router


【解决方案1】:

在您的 &lt;BlogPage /&gt; 组件中添加以下内容

    const { name } = useParams();`

【讨论】:

    【解决方案2】:

    Route 具有component 属性,您可以在其中注入组件。

    <Router>
        <Route path="/blog/:name" component={BlogPage} />
    </Router>
    

    在您的BlogPage 组件中,您可以像这样访问参数:

    function BlogPage(props) {
      return <h1>Hello {props.match.params.name}!</h1>
    }
    

    查看this 以获取更多信息。

    【讨论】:

      猜你喜欢
      • 2020-03-14
      • 1970-01-01
      • 2019-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      相关资源
      最近更新 更多