问题
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