我正在使用 React.js 开发我的第一个项目,并且在关键事件处理方面遇到了一些问题。看来我正在非常精确地遵循我在网上找到的示例。有人可以看一下并告诉我他们发现了什么问题吗?
var ScreenplayElement = React.createClass({
handleKeyPress: function(e) {
if (e.keyCode == 13) {
e.preventDefault();
console.log("New action to be created");
}
},
render: function () {
var classString = this.props.type + " screenplay-el";
return (
<p className={classString} contentEditable onKeyPress={this.handleKeyPress}><br /></p>
);
}
});
最佳答案
尝试改用 KeyboardEvent.key (e.key)。请参阅 Mozilla Docs .
var ScreenplayElement = React.createClass({
handleKeyPress: function(e) {
if (e.key === "Enter") {
e.preventDefault();
console.log("New action to be created");
}
},
render: function () {
var classString = this.props.type + " screenplay-el";
return (
<p className={classString} contentEditable onKeyPress={this.handleKeyPress}><br />Content goes in here</p>
);
}
});
根据 MDN:KeyboardEvent.keyCode 已弃用。
This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.
提示:如果您将 console.log() 消息直接放在 if 语句之前,它将立即触发。这样您就可以确定问题是出在事件处理程序还是 if 语句上:-)
关于javascript - 如何在 React.js 中进行关键事件处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32554575/