How to use onClick event on Link: ReactJS?

前端 未结 2 384
猫巷女王i
猫巷女王i 2020-12-18 21:59

In React router, I have to and onClick attributes as shown below

  • 相关标签:
    2条回答
    • 2020-12-18 22:31

      One possible way is, Instead of using Link, use history.push to change the route dynamically. To achieve that remove the Link component and define the onClick event on li. Now first perform all the task inside onClick function and at the end use history.push to change the route means to navigate on other page.

      In your case change the router inside setState callback function to ensure that it will happen only after state change.

      Write it like this:

      <li key={i} onClick={() => props.selectName(name)}> {name} </li>
      
      selectName = (name) => {
          this.setState({ selectedName:name }, () => {
              this.props.history.push('about');
          });
      }
      

      Check this answers for:

      When to use setState callback

      How to navigate dynamically using react router dom

      0 讨论(0)
    • 2020-12-18 22:35

      Alternatively, I would recommend using URL Params in order to capture the name of the person that the about page is about. Thus, instead of the url being /about and the name being behind the scenes, it would be /about/tom or /about/pushkal. The way that you do this is by defining params in the URL router as such in your index.js:

      <Route path="/about/:name" component={AboutPage}>
      

      Now, when you link to the about page, you would do it as such:

      <Link to={"/about/" + name}>{name}</Link>
      

      Now, in your AboutPage component, you can access the name param as a prop in this.props.params.name. You can look at more examples here.

      This method is a bit different than your current approach but I suspect it will lead to easier design later on

      0 讨论(0)
    提交回复
    热议问题