如何通过按钮单击反应路由器v4在路径上导航?

时间:2017-07-03 04:27:46

标签: javascript reactjs react-router-v4 react-router-dom

我在react-router-dom中有这些路径:

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

一切正常,现在我的组件中的任何地方我想通过onClick改变路径,这样的代码:

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

我该怎么做?

4 个答案:

答案 0 :(得分:13)

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

答案 1 :(得分:8)

react-router-dom导出一个名为useHistory的钩子。 只需将其导入并像这样在您的组件中使用它即可:

import React from 'react';
import { useHistory } from 'react-router-dom';

export default () => {
  const history = useHistory();
   
  return (
    <button onClick={() => history.push('/your/path')}>
      Click me
    </button>
  );
};

我正在使用:

  • “反应”:“ ^ 16.13.1”
  • “ react-router-dom”:“ ^ 5.2.0”

查看此帖子以获取更多详细信息:https://ultimatecourses.com/blog/programmatically-navigate-react-router

答案 2 :(得分:5)

如果仅将按钮用于导航,则可以将其替换为<Link /> 1 并应用按钮样式。

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

或者您可以使用<NavLink /> 2

如果使用Material UI,则可以使用以下代码:

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 :(得分:0)

没什么好想的,但它能完成工作

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