【发布时间】:2022-01-19 02:43:15
【问题描述】:
我正在尝试在反应中创建这个单页应用程序,并且我想根据用户名和密码输入是否正确重定向到另一个页面。我尝试了多种方法,例如 这就是我的 CustomerLoginPage 渲染方法的外观: 这就是 handleSubmit() 的样子: 我会在这里遗漏什么?谢谢! 编辑
我设法通过将我的 CustomerLoginPage 从类组件更改为函数组件来解决此问题,然后使用 useHistory 更改页面。
在阅读了有关将路由器用作 HOC 的建议后,我将其从除 index.js 之外的所有文件中删除,并切换到 BrowserRouter 而不是 HashRouter。 这是 CustomerLoginPage 现在的样子: render() {
return (
<div class="App-header">
<NavLink to="/main">
<button id="backButton">Go Back</button>
</NavLink>
<h4>Login with your customer account</h4>
<br />
<input id="customerLoginUsername" placeholder=" Username"></input>
<input id="customerLoginPassword" type="password" placeholder=" Password"></input>
<br />
<button id="customerLoginButton" onClick={this.handleSubmit}>
Login
</button>
<div className="content"></div>
</div>
);
}
}
export default withRouter(CustomerLoginPage);
handleSubmit() {
let usernameInput = document.getElementById('customerLoginUsername');
let passwordInput = document.getElementById('customerLoginPassword');
if (usernameInput.value !== 'customer' || passwordInput.value !== 'customer') {
// alert("Wrong username or password!");
} else {
this.props.history.replace('/customerhomepage');
}
}
function CustomerLoginPage () {
const history = useHistory();
const loginButtonClicked = () =>{
let path = '/customerhomepage';
history.push(path);
}
const backButtonClicked = () => {
let path = '/main';
history.push(path);
}
const handleSubmit = () => {
let usernameInput = document.getElementById('customerLoginUsername');
let passwordInput = document.getElementById('customerLoginPassword');
if (usernameInput.value !== 'customer' || passwordInput.value !== 'customer') {
alert("Wrong username or password!");
} else {
loginButtonClicked();
}
}
return (
<div class="App-header">
<button id="backButton" onClick={backButtonClicked}>Go Back</button>
<h4>Login with your customer account</h4>
<br />
<input id="customerLoginUsername" placeholder=" Username"></input>
<input id="customerLoginPassword" type="password" placeholder=" Password"></input>
<br />
<button id="customerLoginButton" onClick={handleSubmit}>
Login
</button>
<div className="content"></div>
</div>
);
}
export default withRouter(CustomerLoginPage);
【问题讨论】:
标签: reactjs react-router