2016-04-28 44 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