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

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

问题描述

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

var Test = React.createClass({添加:函数(事件){如果(事件.keyCode == 13){alert('添加中....');}},渲染:函数(){返回(<div><input type="text" id="one" onKeyPress={this.add}/>

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

解决方案

我正在使用 React 0.14.7,使用 onKeyPressevent.key 运行良好.

handleKeyPress = (event) =>{if(event.key === '回车'){console.log('输入按这里!')}}渲染:函数(){返回(<div><input type="text" id="one" onKeyPress={this.handleKeyPress}/>

);}

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);

解决方案

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天全站免登陆