[英]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>
);
};
我在用着:
查看這篇文章了解更多詳情: 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.