我正在尝试创建一个登录页面,当使用ReactJS单击Submit
按钮时,该页面将导航到另一个页面。但我遇到了一些问题:
1.在页面加载时,似乎会立即调用事件处理函数,因为在我执行任何操作之前,console.log('clicked')
会出现在开发人员工具中
1.当我点击Submit
按钮时,页面没有改变。
1.当页面更改(或加载)时,开发人员工具中会出现警告
No routes matched location "/"
in Routes (created by App)
in App
尽管在App.js
中的<Routes>
中已经存在/
和/dashboard
的路径
下面是我的代码(这里是CodeSandbox):
// ./App.js
import { HashRouter as Router, Route, Routes } from "react-router-dom";
import Login from "./components/Login";
import Dashboard from "./components/Dashboard";
export default function App() {
return (
<Router>
<div className="App">
<h1>Hello CodeSandbox</h1>
<Routes>
<Route path="/" element={<Login />} />
</Routes>
<Routes>
<Route path="/dashboard" element={<Dashboard />} />
</Routes>
</div>
</Router>
);
}
// ./components/Login.js
import { Button } from "react-bootstrap";
import { useNavigate } from "react-router-dom";
const Login = () => {
const navigate = useNavigate();
const handleClick = (e) => {
console.log("clicked");
navigate("/dashboard");
};
return (
<div>
<form>
<h2>The Login page</h2>
<Button variant="primary" onClick={handleClick()}>
Submit
</Button>
</form>
</div>
);
};
export default Login;
// ./components/Dashboard.js
import React from "react";
const Dashboard = () => {
return (
<div>
<h2>This is the Dashboard page</h2>
</div>
);
};
export default Dashboard;
2条答案
按热度按时间gkn4icbw1#
因为你直接调用函数
onClick = {()=> handleClick(“send anything here”)}
ubof19bj2#
当你像这样调用
onClick = {handleClick()}
时,它会立即触发该函数,但你希望该函数在事件之后调用,那么你可以使用onClick = {()=> handleClick(“send anything here”)}
如果你想传递事件沿着参数,那么使用这个onClick = {(event)=> handleClick(event,“send anything here”)}
如果你不必传递参数,那么使用这个onClick = {handleClick}