[React] 내 맘대로 만드는 Hooks & practice Hooks

10729 단어 ReactReact

useInput

[ valiator로 value 조건 확인하기 ]

import React, { useState } from "react";

const useInput = (initialValue, validator) => {
  const [value, setValue] = useState(initialValue);
  const onChange = (event) => {
    const { target : {value} } = event;
      let willUpdate = true;
      if(typeof validator === "function") {
        willUpdate = validator(value);
      }
      if(willUpdate) {
        setValue(value);
      }
    };
  return { value, onChange };
};

const App = () => {
  const maxLength = (value) => !value.includes('@')
  const name = useInput("Mr.", maxLength);
  return (
    <div className="App">
      <h1>Hello</h1>
      <input placeholder="Name" {...name} />
    </div>
  );
};

export default App;

};

useEffect(func, [])

import React, { useEffect, useState } from "react";



const App = () => {
  const sayHello = () => console.log("hello");
  const [number, setNumber] = useState(0);
  const [aNumber, setANumber] = useState(0);

  useEffect(sayHello)


  return (
    <div className="App">
      <h1>Hello</h1>
      <button onClick={()=>{setNumber(number + 1)}}>{number}</button>
      <button onClick={()=>{setANumber(aNumber + 1)}}>{aNumber}</button>
    </div>
  );
};

export default App;

좋은 웹페이지 즐겨찾기