-
[react] deepDive 9 컴포넌트 분할, 이벤트 처리하기react 2023. 12. 21. 13:24
1. App 컴포넌트를 시작 코드에서 여러개의 작은 컴포넌트로 분할하기
2. 이벤트 처리하기 (form이 제출될 때 reset버튼 이벤트 처리하기) => 이벤트 핸들러 추가
3. 상태관리 시작 (여러 상태 조각들로)
4. 화면에 데이터 출력하기 (데이터 바인딩)
5. 스타일이 지정된 컴포넌트 사용 하거나 모듈 css 파일을 사용하기
step1
각 컴포넌트를 세분화하여 나타내자
각각 역할을 구분하여 세분화 시켜보자
크게 헤더역할을 하는 컴포넌트와 form을 입력하는 컴포넌트와 table로 나타내는 컴포넌트 세가지로 나눌 수 있다
return ( <div> <Header /> <InterestForm /> <ResultTable /> </div> );
step2
css를 재사용 가능하고 관리하기 쉽게 만들자
{props.children}
부모 컴포넌트 내부에서는 자식 컴포넌트 정보에 접근할 수 있다
(컴포넌트의 여는 태그와 닫는 태그 사이의 내용을 포함)
import "./Button.css"; const Card = (props) => { const classes = "button " + props.className; return <button className={classes}>{props.children}</button>; }; export default Button;
className을 여러개 적용시켜주기위해서 classes라는 변수에 담아주었다.
"button " (띄어쓰기 꼭 하기)
<Butto className="buttonAlt"> Reset </Button> <Button>Calculate</Button>
=> 첫번째 버튼에는 button buttonAlt 두개의 css를 적용시켜주었다
=> 두번째 버튼에는 button css가 적용됨
.button { padding: 0.5rem 1rem; border: none; border-radius: 0.25rem; background: linear-gradient(180deg, #1f584b, #17493d); color: #c2e9e0; font-family: 'Roboto Condensed', sans-serif; cursor: pointer; } .buttonAlt { font-family: 'Roboto Condensed', sans-serif; border: none; background: transparent; color: #c2e9e0; cursor: pointer; } button:hover { background: linear-gradient(180deg, #1b5346, #113c32); } .buttonAlt:hover { background: transparent; color: #91e1d0; }
step3
상태올리기
상태를 부모 컴포넌트에서 자식 컴포넌트로 전달하고,자식 컴포넌트에서 이 상태를 변경하려면,
부모 컴포넌트에서 상태를 관리하고,그 상태와 상태를 변경할 함수를 자식 컴포넌트로 전달하는 방식을 사용할 수 있다.
이것을 "상태 올리기"라고 한다1. 부모컴포넌트에서 부모 컴포넌트에서 상태 및 상태 변경 함수 정의 하기
<부모컴포넌트>
const calculateHandler = (userInput) => { } return( <InterestForm onCalculate={calculateHandler} /> )
2.자식 컴포넌트에서 프로퍼티로 전달받은 함수 호출
<자식컴포넌트>
const InterestForm = (props) => { const submitHandler = (event) => { event.preventDefault(); props.onCalculate(userInput); }; return ( <form onSubmit={submitHandler} /> ) }
=> InterestForm에서 제출을 하면
=> calculateHandler 함수가 호출되어
=> 부모 컴포넌트의 상태를 변경할 수 있다
step4
데이터 바인딩하기
리액트의 jsx문법에서는
카멜케이스로 네이밍을 해야하는데
-를 쓰고 싶다면 아래와 같이 [ ] 대괄호 안의 따옴표로 감싸주어야한다
value={userInput["current-savings"]}
data와 initialInvestment를 프로퍼티로 자식 컴포넌트에 보내줌
<부모 컴포넌트>
{userInput && ( <ResultTable data={yearlyData} initialInvestment={userInput["current-savings"]} /> )}
<자식 컴포넌트>
import react, { useState } from "react"; import styles from "./ResultTable.module.css"; const ResultTable = (props) => { return ( <table className={styles.result}> <tbody> {props.data.map((yearData) => ( <tr key={yearData.year}> <td>{yearData.year}</td> <td>{yearData.savingsEndOfYear}</td> <td>{yearData.yearlyInterest}</td> <td> { yearData.savingsEndOfYear - props.initialInvestment - yearData.yearlyContribution * yearData.year } </td> <td>{yearData.yearlyContribution}</td> </tr> ))} </tbody> </table> ); }; export default ResultTable;
Props 구조 분해 : { 중괄호 }
여러 번 props.data 및 props.initialInvestment을 사용하는 대신,
컴포넌트의 시작 부분에서 프로퍼티를 구조 분해하여 코드를 더 깔끔하게 만들 수 있다
import react, { useState } from "react"; import styles from "./ResultTable.module.css"; const ResultTable = ({data,initialInvestment}) => { return ( <table className={styles.result}> <tbody> {data.map((yearData) => ( // props쓰지않고 data로 바로 쓸 수 있음 <tr key={yearData.year}> <td>{yearData.year}</td> <td>{yearData.savingsEndOfYear}</td> <td>{yearData.yearlyInterest}</td> <td> { yearData.savingsEndOfYear - initialInvestment - // props쓰지않고 initialInvestment로 바로 쓸 수 있음 yearData.yearlyContribution * yearData.year } </td> <td>{yearData.yearlyContribution}</td> </tr> ))} </tbody> </table> ); }; export default ResultTable;
'react' 카테고리의 다른 글
[react] deepDive 10 Portals(포탈) (0) 2023.12.22 [react] deepDive 8 리액트 디버깅 (0) 2023.12.20 [react] deepDive 6 리액트 컴포넌트 스타일링 (0) 2023.12.20 [react] DeepDive 5 리액트 state (0) 2023.12.17 [react] DeepDive 4 리액트 state (0) 2023.12.17