How to get textarea value in react

hotbreakb·2022년 6월 11일
0

textarea에 입력된 값을 읽고 저장하는 방법을 알아본다.

시도 방법

  1. e.target.value로 값을 받는다.

    아주 잘 읽힌다.

    문제는 e.target.value를 저장하려고 하는데, 문자 하나 입력할 때마다 렌더링되어서 비효율적이다.

      onChange={(e) => {
        console.log(e.target.value);
      }}
  1. onChangeonMouseout

    textare를 클릭했다가 바깥을 클릭할 때 이벤트가 발생한다. 이렇게 저장해도 잘 돌아간다.

      onMouseOut={(e) => {
        console.log(e.currentTarget.value);
      }}
  1. ref

    값을 읽을 때 매우 유용하다.

  const textareaRef = useRef(null);

  ...
  
      onMouseOut={(e) => {
        handleDescription((textareaRef.current as any).value);
    	}}
🚨 개체가 'null'인 것 같습니다.
textareaRef.current.value에서 에러가 난다.

🚨 'never' 형식에 'value' 속성이 없습니다.
아무리 물음표 연산자로 피하려고 노력해도 에러가 난다.

결국 any를 사용했다.
profile
글쟁이 프론트 개발자, 헬렌입니다.

0개의 댓글