props의 개념
-부모 컴포넌트가 자식 컴포넌트에게 물려준 데이터, 다시 말해 컴포넌트 간의 정보 교류 방법.
-props는 반드시 위에서 아래 방향으로 흐른다. 즉 [부모] -> [자식] 방향으로만 흐른다.(단방향)
-props는 반드시 읽기 전용으로 취급하며, 변경하지 않는다.
prop drilling
-데이터가 전달되는 과정이 반복되는 것이 prop drilling, props가 아래로 뚫고 내려간다.라고 한다. 유지/보수 측면에서 곤란하다.
state를 쓰는 목적 => UI를 바꾸기 위함 (렌더링을 다시)
React안에서 변경되는 값은 반드ㅏ시 state로 선언
리액트는 화면을 렌더링할지를 state의 변화에 따라 결정한다. 단순 변수는 무시한다.
아래는 오늘 연습한 코드들이다.
import React from 'react'
// props를 통해 부모 -> 자식 데이터가 전달됐다.
function Son(props) {
console.log('props', props.motherName, props.grandfatherName)
return <div>나는 {props.motherName}의 아들, {props.grandfatherName}의 손자에요!</div>;
}
// 부모 -> 자식 정보를 전달했다!
function Mother(props) {
const name = '흥부인';
const name1 = props.grandfatherName;
console.log('props', props.grandfatherName)
return <Son motherName = {name} grandfatherName = {name1} />;
}
function Grandfather() {
const name1 = '흥부버지';
return <Mother grandfatherName = {name1} />;
}
function App() {
return <Grandfather />;
}
export default App;
import { useState } from 'react';
function StateEx() {
const [id, setId] = useState('');
const [password, setPassword] = useState('');
const onIdChangeHandler = (event) => {
setId(event.target.value);
};
const onPwChangeHandler = (event) => {
setPassword(event.target.value);
};
return (
<div>
<div>
아이디 : <input type="text" value={id} onChange={onIdChangeHandler} />
</div>
<div>
비밀번호 :{" "}
<input type="password" value={password} onChange={onPwChangeHandler} />
</div>
<button
onClick = {() => {
alert(
`고객님이 입력하신 아이디는 ${id}이며, 비밀번호는 ${password}입니다.`
);
setId("");
setPassword("");
}}
>
로그인
</button>
</div>
);
}
export default StateEx;
import React from 'react'
import { useState } from 'react';
function App() {
const [count, setCount] = useState(0);
const plusButtonClickHandler = () => {
const newPlusCount = count + 1;
setCount(newPlusCount);
};
return (
<div>
<div>{count}</div>
<div>
<button
onClick={() => {
const newCount = count -1;
setCount(newCount);
}}
>
-
</button>
<button onClick={plusButtonClickHandler}>+</button>
</div>
</div>
);
}
export default App
아래는 css를 분리했다.
import React from "react";
import './App.css';
const App = () => {
return (
<div className="app-style">
<div className="component-style">감자</div>
<div className="component-style">고구마</div>
<div className="component-style">오이</div>
<div className="component-style">가지</div>
<div className="component-style">옥수수</div>
</div>
);
};
export default App;
.app-style {
padding: 100px;
display: flex;
gap: 12px;
}
.component-style {
width: 100px;
height: 100px;
border: 1px solid green;
border-Radius: 10px;
display: flex;
align-Items: center;
justify-Content: center;
}
JavaScript 기반이긴 하나 코딩을 하는 데에 문법적인 차질이 잦다.
최대한 빠른 시간 내에 경험을 쌓아야겠다.