React Hooks_part 2.3_useTabs
useTabs 를 배웠다
import "./styles.css";
import React, { useState } from "react";
const content = [
{
tab: "Section1",
content: "I'm the section 1 "
},
{
tab: "Section2",
content: "I'm the section 2 "
}
//배열을 만들어 준다
];
const useTabs = (initialTab, allTabs) => {
const [currentIndex, setCurrentIndex] = useState(initialTab);
if (!allTabs || !Array.isArray(allTabs)) {
return; //배열이 아닐 때 리턴하는 것이다
}
//useState가 항상 initialTab을 갖는 것이다.
return {
currentItem: allTabs[currentIndex],
//값을 넘겨주도록 한다. 그러기 위해선 아래 const tabs = useTabs(0)를
// const tabs = useTabs(0, content)로 바꿔줘야 한다.
changeItem : setCurrentIndex // changeItem 은 기본값이 setCurrentIndex이다
//이것은 state를 업데이트 시켜줄 것이다
};
};
//App
export default function App() {
const { currentItem, changeItem } = useTabs(0, content);
//tab을 사용한다. 기본값은 section1 이다. 현재 선택한 content의 인덱스를 얻어보자
// 예를 들어 0 일때 content[0]을 얻고 싶다는 것이다.
return (
<div className="App">
<h1>Hello CodeSandbox </h1>
{content.map((section, index) => (
//section은 index를 가지고 있다. 따라서 cjhangeItem에 index를 넣어줄 것이다.
//change item은 setCurrent의 state를 바꿔준다.
<button onClick={() => changeItem(index)}>{section.tab}</button>
))}
<div>{currentItem.content}</div>
</div>
);
}
import "./styles.css";
import React, { useState } from "react";
const content = [
{
tab: "Section1",
content: "I'm the section 1 "
},
{
tab: "Section2",
content: "I'm the section 2 "
}
//배열을 만들어 준다
];
const useTabs = (initialTab, allTabs) => {
const [currentIndex, setCurrentIndex] = useState(initialTab);
if (!allTabs || !Array.isArray(allTabs)) {
return; //배열이 아닐 때 리턴하는 것이다
}
//useState가 항상 initialTab을 갖는 것이다.
return {
currentItem: allTabs[currentIndex],
//값을 넘겨주도록 한다. 그러기 위해선 아래 const tabs = useTabs(0)를
// const tabs = useTabs(0, content)로 바꿔줘야 한다.
changeItem : setCurrentIndex // changeItem 은 기본값이 setCurrentIndex이다
//이것은 state를 업데이트 시켜줄 것이다
};
};
//App
export default function App() {
const { currentItem, changeItem } = useTabs(0, content);
//tab을 사용한다. 기본값은 section1 이다. 현재 선택한 content의 인덱스를 얻어보자
// 예를 들어 0 일때 content[0]을 얻고 싶다는 것이다.
return (
<div className="App">
<h1>Hello CodeSandbox </h1>
{content.map((section, index) => (
//section은 index를 가지고 있다. 따라서 cjhangeItem에 index를 넣어줄 것이다.
//change item은 setCurrent의 state를 바꿔준다.
<button onClick={() => changeItem(index)}>{section.tab}</button>
))}
<div>{currentItem.content}</div>
</div>
);
}
아직 눈에 잘 안들어 온다 인덱스 값이 0 1 바뀌는 것은 잘 이해가 안간다...
버튼 누르면 탭이 왔다갔다 하면서 화면에 보인다.
Author And Source
이 문제에 관하여(React Hooks_part 2.3_useTabs), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@angel_eugnen/React-Hookspart-2.3useTabs저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)