React Hooks

useState

정중식 2019. 12. 10. 23:43

더는 클래스형 컴포넌트를 안만들어도됨! 

state함수형 컴포넌트에서 사용가능!!

 

useState 

import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const App = () => {
  const [item, setItem] = useState(1);
  // 항상 두개의 value를 갖고  array로 리턴함 useState()안의 값이 item이 됨
  // item 하나만 갖고싶을경우 => const item = useState(1)[0] 
  const incrementItem = () => setItem(item + 1);
  const decrementItem = () => setItem(item - 1);
  return (
    <div className="App">
      <h1>Hello {item}</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={incrementItem}>Increment</button>
      <button onClick={decrementItem}>Decrement</button>
    </div>
  );
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

useInput

import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";
// validator 로 input 글자 수 제한기능 (검증기능)
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 maxLen = value => value.length <= 10; // 트루 or 펄스 리턴
  const maxLen = value => !value.includes("@"); // @를 포함하지않으면 true반환
  const name = useInput("Mr.", maxLen);
  return (
    <div className="App">
      <h1>Hello</h1>
      <input placeholder="Name" value={name.value} onChange={name.onChange} />

      <input placeholder="Name" {...name} />
      {/* name 안에 있는 모든 것들을 풀어줌 , 첫번째 input의 value, onChange를 작성해준것과 똑같음*/}
    </div>
  );
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

useTabs

  • 버튼1,2 가있는데 클릭하면 내용이 바뀜
import React, { useState } from "react";
import ReactDOM from "react-dom";

const content = [
  {
    tab: "Section 1",
    content: "I'm the content of the Secton 1"
  },
  {
    tab: "Section 2",
    content: "I'm the content of the Secton 2"
  }
];

const useTabs = (initialTab, allTabs) => {
  if (!allTabs || !Array.isArray(allTabs)) {
    return;
  }
  const [currentIndex, setCurrentIndex] = useState(initialTab);
  return {
    currentItem: allTabs[currentIndex],
    changeItem: setCurrentIndex
  };
};

content[0];

const App = () => {
  const { currentItem, changeItem } = useTabs(0, content);
  return (
    <div className="App">
      {content.map((section, index) => (
        <button onClick={() => changeItem(index)}>{section.tab}</button>
      ))}
      <div>{currentItem.content}</div>
    </div>
  );
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);