forked from earthkingman/42Swim
-
Notifications
You must be signed in to change notification settings - Fork 1
Custom Hooks
Yenowme edited this page Dec 18, 2021
·
1 revision
- ์ปค์คํ ํ ์ ์ ์ํด์ ์์ฃผ ์ฌ์ฉ๋๋ state ์กฐ์ ๊ด๋ จ ํจ์๋ค์ ํจ๊ป ๋ฆฌํดํด ์ค๋ณต์ ์ธ ์ฌ์ฉ์ ์ค์ธ๋ค.
import { useState } from "react";
type validatorType = (value: string) => boolean;
const useInput = (
initialValue: string,
validator: validatorType = () => true //๊ธฐ๋ณธ validator๋ฅผ true๋ก ์ค์
) => {
const [value, setValue] = useState(initialValue);
const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const {
target: { value },
} = event;
if (validator(value)) setValue(value);
else setValid(false);
};
return { value, onChange, setValue };
};
export default useInput;
-
Input
ํ๊ทธ๋ฅผ ์ฌ์ฉํ ๋ ์์ฃผ ์ฌ์ฉ๋๋ onChageํจ์๋ฅผ ๋ฆฌํดํ๋๋ก ์ค์ -
validate
ํจ์๋ฅผ ๋๋ฒ์งธ ์ธ์๋ก ๋ฐ์์ input๊ฐ์ ์ ํํ ์ ์๋ค.
export default App(){
const { value, setValue, onChange } = useInput("hi", (value)=>{value.length>30}));
return <input value={value} onChange={onChange}><input/>
}
- ์ด์ ๋ฐ๋ก
onChange
๋ฅผ ๋ง๋ค์ด์ค ํ์๊ฐ ์๋ค.