代码之家  ›  专栏  ›  技术社区  ›  user2924127

通过按钮将路由参数传递到另一页

  •  0
  • user2924127  · 技术社区  · 7 年前

    我正在使用materialui库和react路由器。在我的顶层组件中,我指定了我的路线:

    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>
        )
    }
    
    1 回复  |  直到 4 年前
        1
  •  1
  •   horyd    7 年前

    这个 to 按钮上的道具需要指定确切的路由URL,而不是路径。比如:

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

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

    推荐文章