2016-04-28 122 views
1

我想添加一個react-router鏈接到我正在創建的窗體中的按鍵事件。表單本身如下所示:添加鏈接到按鍵事件

<div className="col-md-6 col-md-offset-3" onKeyPress={e => this._handleKeyPress(e)}> 
    <Paper style={styles.form}> 
     <form role="form"> 
      <div className="text-center"> 
       <h2>Enter Your Details to Login</h2> 
       <div className="col-md-12"> 
        <TextField 
         hintText="Email" 
         floatingLabelText="Email" 
         type="email" 
         errorText={this.state.email_error_text} 
         onChange={e => this.changeValue(e, 'email')} 
         onBlur={this.isDisabled} 
        /> 
       </div> 
       <div className="col-md-12"> 
        <TextField 
         hintText="Password" 
         floatingLabelText="Password" 
         type="password" 
         errorText={this.state.password_error_text} 
         onChange={e => this.changeValue(e, 'password')} 
         onBlur={this.isDisabled} 
        /> 
       </div> 
       <FlatButton 
        containerElement={<Link to="/portal" />} 
        disabled={this.state.disabled} 
        style={{"marginTop": 50}} 
        label="Submit" 
        onClick={e => this.login(e)} 
       /> 
      </div> 
     </form> 
    </Paper> 
</div> 

正如您所看到的,我正在將material-ui按鈕指向下一頁的鏈接。不過,我也想在按Enter鍵提交表單時做類似的事情。目前,我有這個處理的關鍵事件,並登錄:

_handleKeyPress(e) { 
    if (e.key === 'Enter') { 
     if (!this.state.disabled) { 
      this.login(e); 
     } 
    } 
} 

login(e) { 
    createUser(this.state.email, this.state.password); 
} 

但你可以看到有在按鍵功能不發生轉變。

我的問題是我怎麼能把這添加到按鍵事件,以便它也將導致過渡到下一頁?

一如既往,任何幫助將非常感激。

感謝您的時間

+0

您是否嘗試將路由器添加到組件上下文並使用this.context.router.push('yourpath')? – QoP

+0

我該怎麼去做,我只是真的開始使用react-router,所以我對你的意思有點困惑。 – BeeNag

回答

1

這應該如果使用路由器做出反應,並2.0.0+從反應路由器作爲你的路由器記錄進口browserHistory你可以使用這個以及工作

YourComponent.contextTypes = { 
    router: React.PropTypes.object 
}; 


login(e) { 
    createUser(this.state.email, this.state.password); 
    this.context.router.push('yourURL'); 
} 

import { browserHistory } from 'react-router' 

login(e) { 
    createUser(this.state.email, this.state.password); 
    browserHistory.push('yourURL'); 
} 
+0

這對按鈕按下效果很好,但不幸的是從關鍵新聞活動還沒有愛。看來這個事件還沒有開火。你認爲我打電話的方式有問題嗎? – BeeNag

+0

hm ...由於div沒有焦點,因此事件並未觸發,因此您可以嘗試將它綁定到componentDidMount的窗口中,並使用componentWillUnmount將其解除綁定。 – QoP

+0

綁定到窗口事件後添加,但仍然沒有被解僱... – BeeNag