-
[react] onKeyPress deprecatedreact/react 에러 2022. 11. 23. 16:23
input 태그 입력시 버튼 이외에 키보드 엔터키로도 입력할 수 있도록 하기 위해 onKeyPress 를 사용하려고 하였으나 vscode 에서 가운데 줄이 쫙 그어져있었습니다.
왜 이렇게 나오나 찾아보니deprecated 되었네요.
https://developer.mozilla.org/en-US/docs/Web/API/Element/keypress_event
mozilla.org 에서는 키보드 입력 확인 방법을 기존의 onKeyPress 말고 addEventListener 를 이용해서 작성하는 예제를 보여줍니다.
<div> <label for="sample">Focus the input and type something:</label> <input type="text" name="text" id="sample" /> </div> <p id="log"></p>
<예제 html>
const log = document.getElementById('log'); const input = document.querySelector('input'); input.addEventListener('keypress', logKey); function logKey(e) { log.textContent += ` ${e.code}`; }
<예제 javascript>
이런식으로 addEventListener 를 이용하는 방법 외에
onKeyDown 을 이용해서도 엔터키 입력을 확인할 수 있는 방법도 있는것같습니다.
<input type="password" onKeyDown={handleKeyDown}></input>
<onKeyDown 을 이용한 방법>
const handleKeyDown = (event) => { const key = event.code; switch(key){ case 'Enter': PasswordChk(); break; default: } }
<react 17 버전부터는 .code 속성을 사용할 수 있음>
이런식으로 하면 키보드 엔터키를 잘 인식합니다.
22년 11월 23일 기준으로 onKeyPress 사용에는 문제 없지만 deprecated 된 이상 언젠가는 작동하지 않을테니 새로 작성하는 코드에는
onKeyPress를 사용하지 않으려고 합니다.
'react > react 에러' 카테고리의 다른 글
[react] The result of getSnapshot should be cached to avoid an infinite loop at VideoLayout 에러 (0) 2023.01.12