2015-07-01 80 views
1

我試圖用狀態更新一些文本,然後在一段時間後恢復它。我有一個變量「電子郵件」,我正在從輸入框中的值拉。文本正在改變,但「電子郵件」變量顯示爲「未定義」。有什麼我做錯了嗎?React.js:變量在狀態變化時顯示爲undefined

Code: 

    var SignupForm = React.createClass({ 
     getInitialState: function() { 
     return {email: '', submitted: true}; 
     }, 

     render: function() { 
     var email = this.state.value; 
     var text = this.state.submitted ? 'Enter your email to request early access:' : 'Thank you! 
Expect a follow up at '+email+'soon!'; 
     return (
      <div> 

      <h1 className="home-two-question">{text}</h1> 

      <input type="email" className="input_field" ref="email" value={email} /> 

      <a href="#" className="button" onClick={this.saveAndContinue}>Request Invite</a> 
      </div> 
     ) 
     }, 

     saveAndContinue: function(e) { 
     e.preventDefault() 

     // Get values via this.refs 

     email = this.refs.email.getDOMNode().value 
     this.setState({email: email}) 
     this.setState({submitted: !this.state.submitted}); 

     request = $.ajax({ 
       url: "/user", 
       type: "post", success:function(data){ 
       }, 
       data: {'email': email} ,beforeSend: function(data){console.log(data);} 
     }); 

     } 
    }); 

    React.render(<SignupForm/>, document.getElementById('content')); 
+0

'變種的電子郵件= this.state.value;'應該是'變種的電子郵件= this.state.email;' –

+0

當我這樣做,我可以」 t輸入到輸入框中(文本不會出現在輸入框中) – user1072337

+0

我不確定它是否有幫助,但可能不是將值存儲在'render'返回之外的變量中 - 嘗試將狀態變量直接進入'回報'?正如'value = {this.state.email}' –

回答

1

您需要添加到更新更改搜索字段的值的方法。例如:

var SignupForm = React.createClass({ 
    getInitialState: function() { 
    return {email: '', submitted: true}; 
    }, 

    _updateInputValue(e) { 
    this.setState({email: e.target.value}); 
    }, 

    render: function() { 
    var text = this.state.submitted ? 'Enter your email to request early access:' : 'Thank you! Expect a follow up at '+email+'soon!'; 
    return (
     <div> 

     <h1 className="home-two-question">{text}</h1> 

     <input type="text" className="input_field" onChange={this._updateInputValue} ref="email" value={this.state.email} /> 

     <a href="#" className="button" onClick={this.saveAndContinue}>Request Invite</a> 
     </div> 
    ) 
    }, 

    saveAndContinue: function(e) { 
    e.preventDefault() 

    // Get values via this.refs 

    email = this.refs.email.getDOMNode().value 
    this.setState({email: email}) 
    this.setState({submitted: !this.state.submitted}); 

    request = $.ajax({ 
      url: "/user", 
      type: "post", success:function(data){ 
      }, 
      data: {'email': email} ,beforeSend: function(data){console.log(data);} 
    }); 

    } 
}); 

通知_updateInputValueonChange={this._updateInputValue}