如何控制反应路由器上的链接

时间:2019-05-24 14:10:31

标签: reactjs

我正在尝试建立登录名,验证输入和数据,问题是当输入错误时我不知道如何禁用链接。我的意思是我不希望用户名和密码错误时继续登录。

我可以禁用链接吗?或者我需要其他解决方案 我真的想不出另一种解决方案,希望您能帮助我。

import { Link } from 'react-router-dom';
class Index extends Component {
  state = {
    info: {
      email: '',
      password: ''
    },
    login: {
      email: 'Email.@gmail.com',
      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@example.com"
              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;

2 个答案:

答案 0 :(得分:0)

在状态isValueCorrect中添加新字段:

class Index extends Component {
    state = {
        isValueCorrect: false,
        info: {
          email: '',
          password: ''
           },
        login: {
            email: 'Email.@gmail.com',
            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)
  }

答案 1 :(得分:0)

<button type="submit" className="btn btn-secondary mt-3">
          Sign in
</button>

所有您需要删除的链接并保持按钮 然后登录成功后,您可以使用:-

this.props.history.push('/ Profile');

或 从“ react-router-dom”导入{重定向}

<Redirect to='/target' />
相关问题