使用 withRouter:
import { Route, withRouter } from "react-router-dom";
function App(props) {
const handleGoTo = () => {
props.history.push('/home')
}
return (
<div>
<button onClick={handleGoTo}>跳转</button>
<Route path='/home' component={Home} />
</div> );
}
export default withRouter(App);
使用 useHistory:
import { Route, useHistory } from "react-router-dom";
function App() {
const history = useHistory()
const handleGoTo = () => {
history.push('/home')
}
return (
<div>
<button onClick={handleGoTo}>跳转</button>
<Route path='/home' component={Home} />
</div> );
}
export default App;