【问题标题】:React Router with arguments?用参数反应路由器?
【发布时间】:2018-06-11 10:59:01
【问题描述】:

我有这样的路线设置:

<Route path={'/mycomponent'} exact component={MyComponent} />

并使用 ActiveLink 组件导航到它:

import * as React from 'react' 从 'react-router-dom' 导入 { Link }

export interface OwnProps {
  to        : string,
  pathname  : string,
  children  : React.ReactChild
}

const ActiveLink = (props: OwnProps) => {

  const { pathname, to, children } = props

  if (pathname === to) {
    return <span className={ 'active-link active' }>{ children }</span>
  } else {
    return <Link className={ 'active-link in-active' } to={ to ? to : '/' }>{ children }</Link>
  }
}

export default ActiveLink

我想找到一种方法将数据传递给“MyComponent”(最好在道具中),它相当于“/MyComponent?aparam=hello&anotherparam=32”

【问题讨论】:

  • 顺便说一句,如果你的组件不是某个路由的直接后代,当你可以用 withRouter() 包装它并传递给它的相同道具时

标签: reactjs typescript routes react-router react-redux


【解决方案1】:

假设您有以下解释的路线。

<Route path={'/mycomponent'} exact component={MyComponent} />

现在,如果您在路线上重定向,假设

MyComponent?aparam=hello&anotherparam=32

所以在你的 MyComponent 类中,你可以得到两个参数,如下所示

let aparam = this.props.match.params.aparam;
let anotherparam = this.props.match.params.anotherparam;

希望这会有所帮助,如果没有,请详细说明您的问题 Thnaks :)

【讨论】:

    【解决方案2】:

    在路由中定义传递参数是一个好习惯,像这样。

    <Route path={'/mycomponent/:aparam/:anotherparam'} exact component={MyComponent} />
    

    然后您可以导航到 MyComponent 并以这种方式传递参数:

    <Link to="mycomponent/hello/32">{children}</Link>
    

    最后 aparam 和 anotherparam 将通过 prop 值在 MyComponent 中可用

    this.props.match.params.aparam;
    this.props.match.params.anotherparam;
    

    【讨论】:

      猜你喜欢
      • 2017-06-14
      • 2020-10-02
      • 2016-06-02
      • 2017-08-11
      • 1970-01-01
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多