# 컴포넌트
- UI를 설계하는데 쓰이는 독립적이고 재사용 가능한 부품
- 컴포넌트는 함수 컴포넌트와 클래스 컴포넌트가 있다.
- 컴포넌트 내에서 다른 컴포넌트를 호출하여 합성한다.
function App() {
return(
<>
<h1>Youtube</h1>
<Content /> // 컴포넌트
</>
)
}
function Content() {
return (
<div>
<h2>고양이는 액체일까?</h2>
<img
src = "#"
alt = "고양이"
width="100%"
/>
</div>
)
}
#props
- 컴포넌트에 전달되는 인자
function App() {
const irishBeer = {name: 'Guinness', origin: 'Ireland', available: false}
return (
<>
<h1>맥주</h1>
<Beer beer={irishBeer} /> // 지역변수인 irishBeer를 Beer 컴포넌트에 전달
</>
)
}
function Beer(props) {
console.log(props.beer) // props 확인
const beer = props.beer; // props에 전달된 beer를 다시 사용하기 좋게 바꾼다
return (
<>
<ul>
<li>이름: {beer.name}</li>
<li>원산지: {beer.origin}</li>
<li>판매중: {beer.available ? '예' : '아니오'}</li>
</ul>
</>
)
}
# props로 전달받은 배열을 반복문을 통해 출력
const suggested = [
{id: 'a0', title: '고양이는 정말 폭력적일까?'},
{id: 'a1', title: '고양이는 정말 자기가 신이라고 생각할까?'},
{id: 'a2', title: '냥냥펀치는 얼마나 아플까?'},
];
function App() {
return (
<>
<Suggested suggested={suggested} />
</>
)
}
function Suggested(props) {
const suggested = props.suggested;
return(
<>
<h1>Suggested</h1>
<ul>
{suggested.map(item => (
<li key={item.id}>{item.title}</li> // index가 key역할을 하기도 한다.
))}
</ul>
</>
)
}
# children props
- 컴포넌트에 자식 컴포넌트를 추가한다
- 자식 컴포넌트는 props로 관리할 수 있다
function App() {
return (
<Layout>
<Article />
</Layout>
)
}
function Layout(props) {
return (
<>
<h1>Instagram</h1>
<nav>
<ul>
<li>홈</li>
<li>소개</li>
<li>게시물</li>
</ul>
</nav>
{props.children}
</>
)
}
function Article() {
return (
<>
<img
src="#"
alt=""
width="100%"
/>
<p>
<b>bunny</b>
안녕하세요!
</p>
<small>1일 전</small>
</>
)
}
# useContext Hook
- children 컴포넌트에 데이터를 전달하는 Hook이다.
- 상단에 createContext와 useContext를 import해준다.
const AuthContext = createContext();
function App() {
return (
<AuthProvider>
<Layout>
<Article />
</Layout>
</AuthProvider>
)
}
function AuthProvider (props) {
const value = {username: 'bunny'}
return (
<AuthContext.Provider value={value}>
{props.children}
</AuthContext.Provider>
)
}
function Layout(props) {
const auth = useContext(AuthContext);
console.log(auth)
return(
<>
<h1>Instagram</h1>
<nav>
<ul>
<li>홈</li>
<li>소개</li>
<li>게시물</li>
</ul>
</nav>
<p>안녕하세요 {auth.username}님</p>
{props.children}
</>
)
}
function Article() {
const auth = useContext(AuthContext);
console.log(auth)
return (
<>
<img
src='#'
alt=''
width='100%'
/>
<p>
<b>{auth.username} </b>
고양이 나만없어요^00^
</p>
<small>1일 전</small>
</>
)
}
'JavaScript' 카테고리의 다른 글
[React] tailwind 설치하기 (0) | 2023.01.29 |
---|---|
[React] 라우터, useEffect (0) | 2023.01.25 |
React 1일 (0) | 2023.01.17 |
JS 10일차 (0) | 2023.01.03 |
JS 9일차 (0) | 2023.01.03 |
댓글