如何处理ReactJS中的onKeyPress事件? [英] How to handle the `onKeyPress` event in ReactJS?

查看:264
本文介绍了如何处理ReactJS中的onKeyPress事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使onKeyPress事件在ReactJS中起作用?当按下 enter (keyCode=13) 时,它将发出警报.

How can I make the onKeyPress event work in ReactJS? It should alert when enter (keyCode=13) is pressed.

var Test = React.createClass({
    add: function(event){
        if(event.keyCode == 13){
            alert('Adding....');
        }
    },
    render: function(){
        return(
            <div>
                <input type="text" id="one" onKeyPress={this.add} />    
            </div>
        );
    }
});

React.render(<Test />, document.body);

推荐答案

我正在使用React 0.14.7,使用onKeyPressevent.key效果很好.

I am working with React 0.14.7, use onKeyPress and event.key works well.

handleKeyPress = (event) => {
  if(event.key === 'Enter'){
    console.log('enter press here! ')
  }
}
render: function(){
     return(
         <div>
           <input type="text" id="one" onKeyPress={this.handleKeyPress} />
        </div>
     );
}

这篇关于如何处理ReactJS中的onKeyPress事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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