FRONTENDSCHOOL6 / ready-act

멋쟁이사자처럼 파이널프로젝트 16조
MIT License
0 stars 4 forks source link

[R09M App] CreateRoom 페이지 - form 입력값 이슈 #19

Closed jellyjoji closed 1 year ago

jellyjoji commented 1 year ago

내용

ParticipateCounter.jsx 안에 있는 <p ref={isRef}>{count}</p> 요소의current.value 값을 const counterValue = counterRef.current.value 로 받아서 pockethost 에 등록시켜주려고 하고 있으나 요소가 <p>결과값</p> 형식으로 들어와버려서 데이터에 등록을 할수 없습니다. 현재 결과값만을 문자로 받아오고 싶은데 current.value 가 아닌 다른 형식으로 결과값을 받아야 할까요?

function CreateRoom() {

  const formRef = useRef(null);

  const counterRef = useRef(null);

  const handleCreate = async (e) => {
    e.preventDefault();

    // 오류 : counter 에 current.value 가 안찍힌다.
    const counterValue = counterRef.current.value;
    console.log(counterValue);

    const data = new FormData();

    data.append('participateNumber', counterValue);

return ...
}
import { useState } from "react";
import { minus, plus } from '../../src/assets/icons/svg-icons';

function ParticipateCounter({ title, isRef }) {
  const [count, setCount] = useState(0);

  const incrementCount = () => {
    setCount(count + 1);
  };

  const decrementCount = () => {
    setCount(count - 1);
  };

  return (
    <div>
      <label>{title}</label>
      <div className="flex gap-2 float-right p-2 items-center">
        <button type="button" onClick={decrementCount}>
          <img src={minus} alt="minus" />
        </button>

        <p ref={isRef}>{count}</p>

        <button type="button" onClick={incrementCount}>
          <img src={plus} alt="plus" />
        </button>
      </div>
    </div>
  );
};

export default ParticipateCounter;

참고 이미지 (선택)

현재 console.log(counterValue); 가 콘솔에 결과값으로 찍힙니다. 원하는 형식 : 결과값 ‘4’ 만을 받아서 pockethost 에 등록할 예정입니다. image(width="140px")

※ 댓글에 이슈 해결 완료 후 결과 또는 해결 과정 이미지 첨부

jellyjoji commented 1 year ago

문제 원인

참조(Refs) 객체는 current 속성에 문서의 단락(p) 객체를 참조하므로 value를 가지지 않습니다.

const counterValue = counterRef.current.value;
console.log(counterValue);

문제 해결

현재 공유된 참조 객체의 current 속성에 참조된 것은 문서의 단락(p) 요소이므로 textContent 속성을 사용해 내부에 포함된 콘텐츠를 가져온 후 숫자로 변경해야 합니다.

const ParticipateCounterValue = Number(ParticipateCounterRef.current.textContent);
console.log(ParticipateCounterValue); // 숫자 값(예: 2) 출력

이제 숫자 값을 증가시킨 후 방만들기 버튼을 누르면 숫자 값이 출력됩니다.

image