ㅠㅠ요즘들어 기본기가 부족한게 확 느껴진다..ㅠㅠㅠㅠ
나는 코딩을배운지 일년도안됐는데.......... 빨리취업은 하고싶은 마음에 @일단기능부터만들자@~ 하면서 코딩을 해왔기때문에; 우당탕탕 지식이 짬뽕된듯🥰하하하
😬다시 기본부터 차근차근 인강을 들어보자😬
https://stackblitz.com/edit/stackblitz-starters-sl2hv9?embed=1&file=src%2FApp.js
💖커스텀 훅💖
const useInput = (initialValue, validator) => {
const [value, setValue] = useState(initialValue);
const onChange = (event) => {
const value = event.target.value;
let willUpdate = true;
if (typeof validator === 'function') {
willUpdate = validator(value);
}
if (willUpdate) {
setValue(value);
}
};
return { value, onChange };
};
export default function App() {
const maxLen = (value) => value.length <= 10;
const name = useInput('Mr.', maxLen);
console.log(name); //{value: "Mr."}
return (
<div>
<h1>Hello StackBlitz!</h1>
<input placehorder="Name" {...name} />
</div>
);
}
객체 속성명 단축 (object property shorthand)
: 자바스크립트에서 객체를 생성할 때 프로퍼티 이름과 변수 이름이 같다면 중복을 생략할 수 있다 (몰랐음) 따라서 { value }는 { value: value }와 동일
<input placehorder="Name" value={name.value} onChange={name.onChange} />
를
<input placehorder="Name" {...name} />
이렇게해도 무방하다. 이유는 아래 사진을보자.
https://stackblitz-starters-yyc1ed.stackblitz.io
const content = [
{ tab: 'Section 1', content: '저는 Section1의 컨텐트입니다.' },
{ tab: 'Section 2', content: '저는 Section2의 컨텐트입니다.' },
];
//initialTab은 인덱스, allTabs는 content
const useTabs = (initialTab, allTabs) => {
const [currentIndex, setCurrentIndex] = useState(initialTab);
if (!allTabs || !Array.isArray(allTabs)) {
return;
}
return {
currentItem: allTabs[currentIndex],
changeItem: setCurrentIndex,
};
};
export default function App() {
const { currentItem, changeItem } = useTabs(0, content);
return (
<div>
<h1>Hello StackBlitz!</h1>
{content.map((content, index) => (
<button onClick={() => changeItem(index)}>{content.tab}</button>
))}
<div>{currentItem.content}</div>
</div>
);
}
버튼을 클릭하면, index를 넘겨서 changeItem이란 함수가 실행된다. changeItem함수는 setCurrentIndex로, currentItem을 변경하는 useState함수.