Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

javascript - How to get input textfield values when enter key is pressed in react js?

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 ?

Code:

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} />
      )
   }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Check this example:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...