React/Daily

[moneybook]_day1

오늘도 코딩하나 2024. 8. 22. 01:11

1. 중복된 속성

<tbody>
  {payList.map((item, i) => (
    <tr key={i}>
      <td contentEditable suppressContentEditableWarning={true}>{payList[i].date}</td>
      <td contentEditable suppressContentEditableWarning={true}>{payList[i].group1}</td>
      <td contentEditable suppressContentEditableWarning={true}>{payList[i].group2}</td>
      <td contentEditable suppressContentEditableWarning={true}>{payList[i].price1}</td>
      <td contentEditable suppressContentEditableWarning={true}>{payList[i].price2}</td>
      <td contentEditable suppressContentEditableWarning={true}>{payList[i].payment}</td>
      <td contentEditable suppressContentEditableWarning={true}>{payList[i].remark}</td>
    </tr>
  ))}
</tbody>

 

이게 저번까지 했던 소스코드 상태였다.

모든 td에 중복적으로 속성을 적는것은 비효율적이라 생각했지만

쉽사리 해결책을 생각해내지 못했다...

(((하,,, 나 개몬하네~ㅋㅋㅋㅋㅋㅋ)))

 

https://hyunee-p.tistory.com/117

 

Styled-components 태그 속성 한번에 주기

import React from 'react'; import styled from 'styled-components'; const Father = styled.div` display: flex; `; // attrs({key: value, key:value, ...}) // 이런식으로 한번에 태그 속성을 줄수도 있음 const Input = styled.input.attrs({ require

hyunee-p.tistory.com

위 블로그 글을 보고 styled-components를 사용하면 된다는 정보를 획득할 수 있었다!

 

const Input = styled.td.attrs({
    contentEditable: true,
    suppressContentEditableWarning: true
  })``;

 

const Input = styled.td.attrs({

     contentEditable: true,

     suppressContentEditableWarning: true

});

허헣... styled 사용법도 제대로 숙지하지 않은 채 이렇게만 작성했다가 오류를 맛봤다ㅎ

뒤에 백팁으로 빈값으로라도 css를 줘야하는거 잊지말자ㅎ

 

 

2. 입력란 추가

일단 list형태를 별도의 component로 빼주었다.

function PayItem(props) {
  const Input = styled.td.attrs({
    contentEditable: true,
    suppressContentEditableWarning: true
  })``;
  return (
    <tr>
      <Input placeholder="날짜를 입력하세요.">{props.payList.date}</Input>
      <Input>{props.payList.group1}</Input>
      <Input>{props.payList.group2}</Input>
      <Input>{props.payList.price1}</Input>
      <Input>{props.payList.price2}</Input>
      <Input>{props.payList.payment}</Input>
      <Input>{props.payList.remark}</Input>
    </tr>
  )
}

 

!!!여기서 문제!!!

계속해서 새로운 입력란을 추가해줘야하는데 대체 어떻게 해야하는거지?!?!

챗GPT한테 물어..보자...!

아... 나 왜 이걸 몰랐지.....

 

나는 JS에서 했던 것처럼 clone()을 이용해서 동적으로 추가를 해줘야하나 고민했는데

완전 틀린 생각이었다.

 

// Card(component)를 추가하는 함수
  const addCard = () => {
    setCards([...cards, { id: cards.length + 1 }]);
  };

아.... useState를 이용해서 추가해주면 되는거였구나....쿨럭....

 

let payList = useSelector((state) => state.payList);

그런데 생각해보니 나는 useState를 사용하지 않고,

Redux를 활용하기 위해 paySlice.js 파일에 저장된 state를 useSelector을 이용해서 불러왔다.

 

그래 맞아!

그러면 paySlice.js에서 선언한 추가함수를 이용하면 쉽게 추가할 수 있다!

<Button onClick={()=>dispatch(addItem({id:payList.length}))}>목록 추가하기</Button>

새로운 id를 부여하여 항목을 추가!

굿~ 아주잘된다!

이제 수정하고 저장하고 삭제하는 방법을 내일 해봐야겠다~

가즈아~