简体   繁体   English

keyCode 返回“未定义”(反应)

[英]keyCode returns 'undefined' (react)

I'm trying to trigger a function when someone presses 'Enter'.当有人按下“Enter”时,我试图触发 function。 In my function, when I console.log the keyCode, it returns 'undefined'.在我的 function 中,当我控制台记录 keyCode 时,它返回“未定义”。 I've tried.keyCode, .which, .key, .code, but all of them return undefined.我试过.keyCode、.which、.key、.code,但它们都返回未定义。 Here is my code:这是我的代码:

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]
            })
        }
    }

How do I get the value of the keyCode when passing in the event value into the function?将事件值传入 function 时如何获取 keyCode 的值? This is an onChange event.这是一个 onChange 事件。 I've also tried using an onKeyDown event, an onKeyUp event, an onKeyPress event and the keyCode is always 'undefined'.我还尝试过使用 onKeyDown 事件、onKeyUp 事件、onKeyPress 事件,并且 keyCode 始终为“未定义”。

Here is the element it is bind to:这是它绑定到的元素:

<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)}/>

You don't pass the event object to handleLineCount :您没有将event object 传递给handleLineCount

<textarea onKeyPress={handleLineCount} />

编辑节日-lalande-rfw2j

Here you have more about events in react在这里你有更多关于反应中的事件

But long story short:但长话短说:

use nativeEvent to access keyCode, since event in arguments is synthetic event sent by react and in there you have event.nativeEvent.keyCode使用nativeEvent访问 keyCode,因为 arguments 中的事件是由 react 发送的合成事件,在那里你有event.nativeEvent.keyCode

EDIT编辑

You should pass only e to function not e.target.value您应该只将 e 传递给 function 而不是 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)}
/>

You need to send the event.keyCode , not the event.target.value ....您需要发送event.keyCode ,而不是event.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"
     onKeyDown={e => this.handleLineCount(e.keyCode)}
    />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM