繁体   English   中英

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

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

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

我怎样才能做到这一点?

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

如果您仅将按钮用于导航,则可以将其替换为<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";

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”
  • “反应路由器 dom”:“^5.2.0”

查看这篇文章了解更多详情: https ://ultimatecourses.com/blog/programmatically-navigate-react-router

react-router-dom 版本 6中使用useNavigate

import { useNavigate } from "react-router-dom";
import { Button } from "@mui/material";
...
const navigate = useNavigate();
<Button
   onClick={() => navigate("/your-path-here")}>
click me
</Button>

不要忘记从mui.com安装以使用<Button></Button>组件

在 react-router-dom 版本 6 中,您也可以使用 Link 组件。 这是为了支持@Abey Bruck 的回答

import { Button } from "@chakra-ui/react";
...

const Home = () => {
  return (
    <Button as={Link} to={'/login'}>Login Page</Button>
  )
}
import { Button } from "@mui/material";
const navigate = useNavigate();
  const submitHandler = (e) => {
    e.preventDefault();
    navigate(`/`);
  };
<Button variant="contained" onClick={submitHandler}>Home Page</Button>

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

我怎样才能做到这一点?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM