在 React 中按下回车键时如何获取 TextField 值?

How to get the TextField value when enter key is pressed in React?

我想在用户按键盘上的回车键时传递 TextField 值。在 onChange() 事件中,我得到了 textbox 的值,但是当按下 enter 键时如何得到这个值?

代码:

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} />
      )
   }
}

html

<input id="something" onkeyup="key_up(this)" type="text">

script

function key_up(e){
    var enterKey = 13; //Key Code for Enter Key
    if (e.which == enterKey){
        //Do you work here
    }
}

下次请尝试提供一些代码。

使用onKeyDown事件,并在其中检查用户按下的键的键码。 Enter键的键码是13,检查代码,把逻辑放在那里。

检查这个例子:

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' />

注意:input 元素替换为 Material-Ui TextField 并定义其他属性。

添加 onKeyPress 将适用于文本字段中的更改。

<TextField
  onKeyPress={(ev) => {
    console.log(`Pressed keyCode ${ev.key}`);
    if (ev.key === 'Enter') {
      // Do code here
      ev.preventDefault();
    }
  }}
/>
<input onKeyPress={onKeyPress}/> 

const onKeyPress = (e: any) => { if (e.which == 13) { // your function }};

如果您使用 uncontrolled 模式,您可以使用 e.target.value 获取 input 元素的当前值。

<TextField
  onKeyPress={(e) => {
    if (e.key === 'Enter') {
      alert(e.target.value);
    }
  }}
/>

现场演示