how to navigate to different page on click of a button in React functional components?

橙三吉。 提交于 2021-02-11 14:41:42

问题


I know we can use to wrap our components but what is the way to route to a new page on click of a button in React functional components?


回答1:


Try this,

React Router has now useHistory hook for functional components:

Docs: https://reacttraining.com/react-router/web/api/Hooks/usehistory

import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button onClick={handleClick}>
      Navigate
    </button>
  );
}

export default HomeButton;



回答2:


for this situations you can code like so :


import {withRouter} from 'react-router-dom';

const App = ({history , ...rest}) => {

 const changeRoute = () => {
      history.push("/new_route");
   }

  return (
      <div>
         <button onClick={changeRoute}>i will change route</button>
      </div>

   )
}

export default withRouter(App);




来源:https://stackoverflow.com/questions/60427306/how-to-navigate-to-different-page-on-click-of-a-button-in-react-functional-compo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!