Javascript keyCode返回';未定义';(反应)
当有人按下“回车”键时,我试图触发一个函数。在我的函数中,当我在console.log中记录keyCode时,它返回“undefined”。我尝试了.keyCode、.which、.key、.code,但它们都返回未定义的。这是我的密码:Javascript keyCode返回';未定义';(反应),javascript,reactjs,Javascript,Reactjs,当有人按下“回车”键时,我试图触发一个函数。在我的函数中,当我在console.log中记录keyCode时,它返回“undefined”。我尝试了.keyCode、.which、.key、.code,但它们都返回未定义的。这是我的密码: handleLineCount = (event) => { console.log(event.keyCode); let charCount = event.length; let myIndex =
handleLineCount = (event) => {
console.log(event.keyCode);
let charCount = event.length;
let myIndex = 0;
this.setState({
charCount: charCount,
});
if(charCount === 5 && event.keyCode !== 8 || event.keyCode === 13){
myIndex++;
this.setState({
lines: [...this.state.lines, myIndex]
})
}
}
在将事件值传递到函数中时,如何获取keyCode的值?这是一个onChange事件。我还尝试过使用onKeyDown事件、onKeyUp事件、onKeyPress事件,并且keyCode总是“未定义”
以下是绑定到的元素:
<textarea
id="first-line"
placeholder="this is a test to count line numbers..."
style={{width: "60%", padding: "10px 10px 0", boxSizing: "border-box"}}
maxlength="5"
onChange={(e) => this.handleLineCount(e.target.value)}/>
this.handleLineCount(e.target.value)}/>
这里有更多关于react的信息
但长话短说:
使用nativeEvent
访问keyCode,因为参数中的事件是react发送的合成事件,其中有event.nativeEvent.keyCode
编辑
您应该只将e传递给函数,而不是e.target.value
<textarea
id="first-line"
placeholder="this is a test to count line numbers..."
style={{width: "60%", padding: "10px 10px 0", boxSizing: "border-box"}}
maxlength="5"
onChange={(e) => this.handleLineCount(e)}
/>
this.handleLineCount(e)}
/>
您没有将事件
对象传递给handleLineCount
:
<textarea onKeyPress={handleLineCount} />
您需要发送
事件.keyCode
,而不是事件.target.value
this.handleLineCount(e.keyCode)}
/>
您可以添加绑定到函数的元素吗?请尝试
console.log(Object.keys(event))
查看itI中有哪些内容我刚刚添加了绑定到Object.keys(event)的元素返回空数组您可以使用codepen或codesandbox为此创建一个数组以显示发生的问题。仅尝试了此操作并获得错误代码:无法读取undefinedjust的属性“keyCode”,尝试仅将e与.nativeEvent.keyCode一起传递,但仍在文本区域onChange={this.handleLineCount}
,在功能上(event)=>{console.log(event.nativeEvent)}
并查看它的日志很高兴听到这一点,请将此答案标记为解决方案您不需要nativeEvent
刚刚尝试了这个方法,并且按键代码仍然返回“未定义”使用其他事件,而不是onChange
,请参阅附件示例此方法有效!谢谢我将onKeyPress函数放在类组件中,并使用附加到onKeyPress事件的this.onKeyPress。还使用了console.log中的.nativeEvent.keyCode。@DennisVash为什么要使用onKeyPress
而不是onChange
?@JuniusL。感谢您的投票否决,您没有此事件的keyCode
(至少我检查了),请检查沙箱
<textarea
id="first-line"
placeholder="this is a test to count line numbers..."
style={{width: "60%", padding: "10px 10px 0", boxSizing: "border-box"}}
maxlength="5"
onKeyDown={e => this.handleLineCount(e.keyCode)}
/>