gpt4 book ai didi

javascript - 你如何在 React.js 中进行关键事件处理?

转载 作者:行者123 更新时间:2023-11-29 21:41:48 26 4
gpt4 key购买 nike

我正在使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com