【问题标题】:Passing route parameter through button to another page通过按钮将路由参数传递到另一个页面
【发布时间】:2019-03-06 02:21:21
【问题描述】:

我正在使用 materialui 库和 react-router。在我的顶级组件中,我指定了我的路线:

class App extends Component {
  render() {
    const {classes} = this.props;
    return (
      <React.Fragment> 
        <BrowserRouter>
          <Route render={({location}) => (
          <TransitionGroup>
          <CSSTransition
              key={location.key}
              timeout={100}
              classNames="someanimation"
            >
          <Switch location={location}>
               <Route exact path="/" component={HomePage} />
               <Route exact path="/customer/:id" component={CustomerPage} />
               <Route component={ErrorPage} />
             </Switch>
           </CSSTransition>
         </TransitionGroup>
       )} />
        </BrowserRouter>
     </React.Fragment>
    );
  }
}

在我的主页上,我有一些按钮对应一些客户。当我单击该按钮时,它现在应该使用该客户 ID 转到客户页面。我的主页按钮如下所示:

<Button component={Link} to="/customer/:id">
                      Go To Customer id : {this.props.customer[100]}
                    </Button>

从这里我不确定如何将客户 ID 从此按钮传递到客户页面?

我的客户页面很简单,如下所示:

const Customer= () => {
    return(
        <div >
            <h3>Customer ID : {somehow get the id that was passed in here}</h3>
        </div>
    )
}

【问题讨论】:

  • React 路由器有一个匹配道具,可以从 URL 传递参数。所以如果你有一个叫id的道具,它应该是this.props.match.params.id
  • 在按钮上如何指定要传递的 id?
  • 你的'to='/customer/${this.props.customer[100]}''。您必须将值传递给链接。只需用字符串文字替换引号

标签: reactjs react-router material-ui


【解决方案1】:

按钮上的 to 属性需要指定确切的路由 URL,而不是路径。所以像:

<Button component={Link} to="/customer/100">

然后正如 cmets 中提到的 Strahinja Ajvaz,您可以在您的 Customer 组件中使用 this.props.match.params.id 来检索该 ID

【讨论】:

  • 它似乎不起作用。我的按钮现在看起来像这样:
  • 所以我将其更改为 match.params.id,如果我直接输入 url(例如 customer/100)它会显示,从我的按钮设置它仍然不适用于动态 ID。是的,如果我把 to="/customer/100" 但我需要它来允许一个表达式,因为 id 不是硬编码的字节动态
  • 弄明白了:to={'/customer/' + customer[100]}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-24
  • 1970-01-01
  • 2011-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多