component
- 여러 개의 프로그램 함수들을 모아 하나의 특정한 기능을 수행할 수 있도록 구선한 작은 기능적 단위를 말한다. 컴퍼넌트를 이용하면 소프트웨어 개방을 마치 레고 블록을 쌓듯이 조립식으로 쉡게 할 수 있다.
컴퍼넌트는 프로그램의 한 부분을 의미하며 재사용이 가능한 최소 단위를 말하며 모듈이라고도 한다.
예)
function MinutesToHours() { //자식 컴퍼넌트
const [amouny, setAmouny] = React.useState(0);
const [flipped, setFlipped] = React.useState(false);
const onChange = (event) => {
setAmouny(event.target.value);
};
const reset = () => setAmouny(0);
const onFlip = () => {
reset();
setFlipped((current) => !current);
};
return (
<div>
<h3>시 & 분</h3>
<div>
<label htmlFor="hours"> 시: </label>
<input
value={flipped ? Math.floor(amouny / 60) : amouny}
id="hours"
type="number"
onChange={onChange}
disabled={flipped}
/>
</div>
<div>
<label htmlFor="minures">분: </label>
<input
value={flipped ? amouny : amouny * 60}
id="minures"
type="number"
onChange={onChange}
disabled={!flipped}
/>
</div>
<button onClick={reset}>Reset</button>
<button onClick={onFlip}>Flipped</button>
</div>
);
}
function App() { //부모 컨퍼넌트
const [index, setIndex] = React.useState("0");
const onSelect = (event) => {
setIndex(event.target.value);
};
return (
<div>
<h1 className="h1">Super converter</h1>
<select onChange={onSelect}>
<option value="0">시간 & 분</option>
<option value="1">Km & M</option>
</select>
<hr />
{index === "0" ? <MinutesToHours /> : <KmToM />} <!--자식 컨처넌트를 불러옴-->
</div>
);
}
const root = document.getElementById("root");
ReactDOM.render(<App />, root);
props
- 부모 컴포넌트로부터 자식 컴포넌트에 테이터를 보낼 수 있게 해주는 방법이다. 자식 컴포넌트에는 파라미터 자리에 적고 부모 컴포넌트는 호출한 자식 컴포넌트 명 뒤에 입력하면 된고 객체 형태로 반환한다.
자식 컴퍼넌트에 {}를 넣고 안에 키를 적으면 동일한 키의 값을 반환한다.
예)
function Btn({ text, big }) { //props
return <button style={{
backgroundColor: "green",
color: "white",
padding: "10px 20px",
border: 0,
borderRadius: 10,
fontSize: big ? 18 : 15,
}}>{text}</button>
}
function App() {
return (
<div>
<Btn text="Save Change" big="true"/> {/* props */}
<Btn text="Continue" />
</div>
);
}
공부한 곳! - 노마드 코더 'ReactJS로 영화 웹 서비스 만들기'
'React' 카테고리의 다른 글
Reat 6 To-Do-List (preventDefault(), trim(), JSX에서 JS 내장함수 사용하기) (0) | 2023.01.18 |
---|---|
React 5 useEffect (0) | 2023.01.16 |
React 4 React 준비 (0) | 2023.01.16 |
React 3 Memo, prop Types (0) | 2023.01.14 |
React 1 useState() (0) | 2023.01.10 |