Javascript 如何通过点击反应路由器 v4 中的按钮在路径上导航?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44877821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:46:22  来源:igfitidea点击:

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

javascriptreactjsreact-router-v4react-router-dom

提问by gpbaculio

I have this paths in react-router-dom:

我在 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:

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

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

how can I do that?

我怎样才能做到这一点?

回答by soywod

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

回答by frogatto

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

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

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

Or you can use the <NavLink />2.

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

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

在使用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";

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

回答by Noah Franco

Nothing fancy but it gets the job done

没什么特别的,但它可以完成工作

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