在React JS中按下Enter键时如何获取输入文本字段值? [英] How to get input textfield values when enter key is pressed in react js?

查看:698
本文介绍了在React JS中按下Enter键时如何获取输入文本字段值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用户按下键盘上的Enter键时传递textfield值.在onChange()事件中,我正在获取textbox的值,但是如何在按下enter键时获取该值?

I want to pass textfield values when user press enter key from keyboard. In onChange() event, I am getting the value of the textbox, but How to get this value when enter key is pressed ?

代码:

import TextField from 'material-ui/TextField';

class CartridgeShell extends Component {

   constructor(props) {
      super(props);
      this.state = {value:''}
      this.handleChange = this.handleChange.bind(this);
   }

   handleChange(e) {
      this.setState({ value: e.target.value });
   }

   render(){
      return(
         <TextField 
             hintText="First Name" 
             floatingLabelText="First Name*"
             value={this.state.value} 
             onChange={this.handleChange} 
             fullWidth={true} />
      )
   }
}

推荐答案

使用onKeyDown事件,并在其中检查用户按下的键的键控代码. Enter键的键代码为13,检查代码并在其中放置逻辑.

Use onKeyDown event, and inside that check the key code of the key pressed by user. Key code of Enter key is 13, check the code and put the logic there.

检查此示例:

class CartridgeShell extends React.Component {

   constructor(props) {
      super(props);
      this.state = {value:''}

      this.handleChange = this.handleChange.bind(this);
      this.keyPress = this.keyPress.bind(this);
   } 
 
   handleChange(e) {
      this.setState({ value: e.target.value });
   }

   keyPress(e){
      if(e.keyCode == 13){
         console.log('value', e.target.value);
         // put the login here
      }
   }

   render(){
      return(
         <input value={this.state.value} onKeyDown={this.keyPress} onChange={this.handleChange} fullWidth={true} />
      )
    }
}

ReactDOM.render(<CartridgeShell/>, document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>


<div id = 'app' />

注意:用Material-Ui TextField替换input元素,并定义其他属性.

Note: Replace the input element by Material-Ui TextField and define the other properties also.

这篇关于在React JS中按下Enter键时如何获取输入文本字段值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆