2015-12-05 83 views
0

我正在嘗試對基於電子郵件的輸入實施一些驗證。它主要在那裏,但我遇到了一個奇怪的情況。React - 輸入值清除提交

我正在剔除onChange函數,它包含一些驗證並在提交時再次驗證。如果用戶在debounce捕獲之前提交了一個無效的字符串,submit函數將捕獲它並將組件狀態設置爲無效,但只有在去抖動到達之前,此時去抖動纔將狀態恢復爲有效,因爲它看起來像表單提交將清除輸入字段的基礎值。我的提交函數中有一個preventDefault,但它似乎仍然像event.target在提交函數被觸發時被清空。我想保持event.target/input值同步。這裏是我的代碼:

import React from 'react'; 
import {Link} from 'react-router'; 
import _ from 'underscore'; 
import classNames from 'classnames'; 

class Search extends React.Component { 
    constructor(props) { 
     super(props); 

     this.state = { 
      isValid: true 
     }; 
     this.validateOnChange = _.debounce(this.validateOnChange,500).bind(this); 
     this.handleSubmit = this.handleSubmit.bind(this); 
     this.validateEmail = this.validateEmail.bind(this); 
    } 


    handleSubmit(event) { 
     event.preventDefault(); 

     if(this.validateEmail(event.target[0].value)){ 
      $.ajax({ 
       url: '/api/search?email=' + event.target[0].value 
      }) 
      .done((data) => { 
       this.props.getNewImage(data, false); 
      }) 
      .fail(() => { 
       this.props.getNewImage('/img/obi.gif', true); 
      }); 
     }else { 
      this.setState({isValid: false}); 
     } 
    } 

    validateOnChange(event){ 
     this.setState({isValid: (event.target.value ? this.validateEmail(event.target.value) : true)}); 
    } 

    validateEmail(input){ 
     var re; 
     re = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b/i; 

     return re.test(input); 
    } 

    render() { 
     var classes = classNames({ 
      'form-control': true, 
      'valid': this.state.isValid, 
      'invalid': this.state.isValid === false 
     }); 
     return(
      <form ref='searchForm' className='navbar-form navbar-left animated' onSubmit={this.handleSubmit.bind(this)}> 
       <div className='input-group'> 
        <input type='text' className={classes} placeholder="Enter Email!" onChange={this.validateOnChange.bind(this)} /> 
        <span className='input-group-btn'> 
         <button className='btn btn-default' type="submit"><span className='glyphicon glyphicon-search'></span>Search</button> 
        </span> 
       </div> 
       {this.state.isValid ? null : <span className="invalid-text">Invalid Email Address</span> } 
      </form> 
     ); 
    } 
} 

export default Search; 
+0

這是否適合您? http://jsbin.com/motehejuwa/edit?js,output –

回答

0

您可以使用react/linkStatelinkState來處理輸入元素的onChange事件。

<input 
    min="1" 
    max="10" 
    type="number" 
    className="form-control" 
    valueLink={linkState(this, 'qty')} />