web-dev-qa-db-fra.com

Comment naviguer sur le chemin par clic de bouton dans Reactor Router v4?

J'ai ces chemins dans react-router-dom:

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

tout fonctionne bien, maintenant n'importe où dans mes composants, je veux changer de chemin par onClick, un code comme celui-ci:

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

comment puis je faire ça?

13
i am gpbaculio
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);
22
soywod

Si vous utilisez le bouton uniquement pour la navigation, vous pouvez le remplacer par <Link />1 et appliquez un style de bouton.

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

Ou vous pouvez utiliser le <NavLink />2.

En cas d'utilisation de Material UI , vous pouvez utiliser le code suivant:

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";

9
frogatto