How to navigate on path by button click in react router v4?

旧城冷巷雨未停 提交于 2020-01-30 18:20:08

问题


I have this paths in react-router-dom:

 <BrowserRouter>
  <div>
  <Route exact path='/(index.html)?' component={Home}/> {/* app = home */}
  <Route  path='/register' component={Registration}/>
  </div>
</BrowserRouter>

everything is working fine, now anywhere in my components I want to change path by onClick, a code like this:

<button onClick={() => history.push('/the/path') }> change path </button>

how can I do that?


回答1:


import {withRouter} from 'react-router-dom';
...

class App extends React.Component {
  ...

  nextPath(path) {
    this.props.history.push(path);
  }

  render() {
    return (
      <button onClick={() => this.nextPath('/the/path') }>
        change path 
      </button>
    );
  }
}

export default withRouter(App);



回答2:


If you're using the button only for navigation, you can replace it with <Link />1 and apply a button style.

<Link to='/new/location/'>Click Me</Link>

Or you can use the <NavLink />2.

In case of using Material UI, you can use the following code:

import { Link } from 'react-router-dom'
import Button from '@material-ui/core/Button';

<Button component={Link} to="/new/location/">
  Click Me
</Button>

(1): import {Link} from "react-router-dom";
(2): import {NavLink} from "react-router-dom";




回答3:


Nothing fancy but it gets the job done

 `<a href="http://localhost:3001/contact">  
      {" "}
      Contact Us{" "}
      </a>` 


来源:https://stackoverflow.com/questions/44877821/how-to-navigate-on-path-by-button-click-in-react-router-v4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!