如果出错,React Js会在输入旁边附加div

时间:2016-07-22 07:51:20

标签: reactjs

我刚刚开始使用reactJs,我发现它很混乱。

我登录了帖子,如果用户输入密码,它返回代码200.但我不明白的是我怎么能在输入旁边添加/添加/显示错误(在Jquery中很容易但在这里我似乎无法看到弄明白)。

到目前为止我已经

render: function() {

        <div>
             <label for="username">User:</label>
             <input type="text" ref='username' id='username' type='text'/>
             <label for="password">Password:</label>
             <input ref='password' id='password' type='password' errorMessage="Password is required"/>
             <a onClick={this.submit} className="btn btn-primary">Login</a>
       </div>
},

submit: function() {

       var username = ReactDOM.findDOMNode(this.refs.username).value;
       var password = ReactDOM.findDOMNode(this.refs.password).value;
       this.serverRequest = $jQuery.post(url, { username: username, password: password }, function (data,success,type) {

       if(type.status == 200){
          console.log('Good');
          this.props.func(); //this is from parent which changes state of login to true
       }
       else{
             console.log('Wrong password/username');

        //Show error next/under password input
       } 
      }.bind(this));
}

2 个答案:

答案 0 :(得分:2)

您可以使用this.setState。因此,当它出错时,将变量设置为true / false。

e.g。在这一行之后:

console.log('Wrong password/username');

添加

this.setState({ error: true });

然后在render()方法中,使用简单的if语句

render: function() {
   var errorMsg;
   if (this.state.error)
     errorMsg = <span className="error-msg">Error</span>;

   return (
     <div>
       <label for="username">User:</label>
             <input type="text" ref='username' id='username' type='text'/>

             <label for="password">Password:</label>
             <input ref='password' id='password' type='password' errorMessage="Password is required"/>
             {errorMsg}
   // ....
   );
}

答案 1 :(得分:1)

只需在状态中保留一个标志,并在出现错误时将其打开

render: function() {

        return (<div>
             <label for="username">User:</label>
             <input type="text" ref='username' id='username' type='text'/>

             <label for="password">Password:</label>
             <input ref='password' id='password' type='password' errorMessage="Password is required"/>

             {this.state.errors ? <div >Errors </div> : null}
             <a onClick={this.submit} className="btn btn-primary">Login</a>

       </div>)
}


submit: function() {

var username = ReactDOM.findDOMNode(this.refs.username).value;
var password = ReactDOM.findDOMNode(this.refs.password).value;

this.serverRequest = $jQuery.post(url, { username: username, password: password }, function (data,success,type) {

  if(type.status == 200){
     console.log('Good');

      this.props.func(); //this is from parent which changes state of login to true
  }
  else{
    console.log('Wrong password/username');
        this.setState({
        errors: true
       });
        //Show error next/under an input
  }

}.bind(this));

}