使用 React Router 以程式設計方式導覽
在 React Router 中,Link 元素支援使用超連結進行本機導覽。但是,對於連結之外的程式設計導航,您可以利用以下方法。
React Router v6.6.1 及更高版本:useNavigate Hook
使用useNavigate 鉤子,如下圖所示:
import { useNavigate } from "react-router-dom"; function HomeButton() { const navigate = useNavigate(); function handleClick() { navigate("/home"); } return ( <button type="button" onClick={handleClick}> Go home </button> ); }
import { useHistory } from "react-router-dom"; function HomeButton() { const history = useHistory(); function handleClick() { history.push("/home"); } return ( <button type="button" onClick={handleClick}> Go home </button> ); }
import { withRouter } from "react-router-dom"; const Button = withRouter(({ history }) => ( <button type="button" onClick={() => { history.push("/new-location") }} > Click Me! </button> ));
import { Route } from "react-router-dom"; const Button = () => ( <Route render={({ history }) => ( <button type="button" onClick={() => { history.push("/new-location") }} > Click Me! </button> )} /> );
const Button = (props, context) => ( <button type="button" onClick={() => { context.history === history.push === history.push; context.history.push('/new-location') }} > Click Me! </button> ); Button.contextTypes = { history: PropTypes.shape({ push: PropTypes.func.isRequired }) };
以上是如何以程式設計方式在 React Router v4、v5 和 v6 中導航?的詳細內容。更多資訊請關注PHP中文網其他相關文章!