我正在尝试构建一个登录,我验证输入和数据,问题是我不知道如何在输入错误时禁用链接。 我的意思是当用户名和密码错误时我不希望登录继续。
我可以禁用链接吗? 或者我需要另一种解决方案我真的想不出另一种解决方案,希望你能帮助我。
import { Link } from 'react-router-dom';
class Index extends Component {
state = {
info: {
email: '',
password: ''
},
login: {
email: '[email protected]',
password: '1234'
}
};
updateInfo = e => {
this.setState({
info: { ...this.state.login, [e.target.name]: e.target.value }
});
};
submit = e => {
e.preventDefault();
if (
this.state.info.email === this.state.login.email &&
this.state.info.password === this.state.login.password
) {
console.log('true');
} else {
console.log('false');
}
};
render() {
return (
<div className="text-center container mt-4" style={{ width: '50%' }}>
<form className="px-4 py-3" onSubmit={this.submit}>
<div className="form-group">
<label>Email: </label>
<input
type="text"
placeholder="[email protected]"
className="form-control"
name="email"
value={this.state.info.email}
onChange={this.updateInfo}
/>
</div>
<div className="form-group">
<label>Password: </label>
<input
type="text"
placeholder="Password"
className="form-control"
name="password"
value={this.state.info.password}
onChange={this.updateInfo}
/>
</div>
<Link to="Profile">
<button type="submit" className="btn btn-secondary mt-3">
Sign in
</button>
</Link>
<div>
<Link to="/register" className="badge badge-light p-2 m-2">
Register
</Link>
</div>
</form>
</div>
);
}
}
export default Index;
在状态isValueCorrect中添加新字段:
class Index extends Component {
state = {
isValueCorrect: false,
info: {
email: '',
password: ''
},
login: {
email: '[email protected]',
password: '1234'
}
};
然后检查密码的值并在updateInfo中登录,如果登录和密码正确,请调用this.setState({isValueCorrect:true})方法然后在组件中使用简单的if语句,如下所示:
{ this.state.isValueCorrect === true ?
( <Link to="Profile">
<button type="submit" className="btn btn-secondary mt-3">
Sign in
</button>
</Link>)
:
(null)
}
<button type="submit" className="btn btn-secondary mt-3"> Sign in </button>
所有你需要删除链接并保持按钮然后登录成功后,你可以使用: -
this.props.history.push( '/资料');
或者从'react-router-dom'导入{Redirect}
<Redirect to='/target' />