【发布时间】:2020-09-15 19:19:47
【问题描述】:
我在使用 react-router-dom 在屏幕之间导航时遇到问题。我想做的是在完成一个动作后我想导航到其他屏幕。很抱歉这个菜鸟问题,但这是我第一次使用 react。
【问题讨论】:
-
到目前为止你尝试了什么?
标签: reactjs web-applications screen router
我在使用 react-router-dom 在屏幕之间导航时遇到问题。我想做的是在完成一个动作后我想导航到其他屏幕。很抱歉这个菜鸟问题,但这是我第一次使用 react。
【问题讨论】:
标签: reactjs web-applications screen router
如果你使用钩子,请使用 react-router dom useHistory hook https://reactrouter.com/web/api/Hooks
例如:
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
【讨论】:
尝试使用这些命令
this.props.history.push("/Home")// use this for class component
props.history.push("/Home")// functional component (and pass props to the component)
例子:
function LoginComponent(props) {
const handleClick=()=> {
props.history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
并确保您在 app.js 中编写了路由
import { BrowserRouter as Router, Route } from "react-router-dom";
import Home from "./components/Home";
<Router>
<Route path="/home" component={Home} />
</Router>
【讨论】: