단순 코드 기록/React

React_reducer_자식창 연동 ADD/DEL

일일일코_장민기 2024. 3. 19. 10:04
728x90
App
import { createContext, useReducer, useState } from "react"
import Button from "./components/Button"

export const UserContext = createContext(null);

export default function App(){

  const reducer = (current_state, action) => {    //current_state: 현재 배열 상태
                                                  //action: type(타입명: ADD / DEL) / xxx(추가되는 값)
    console.log(">>>" , current_state.filter((v,i) => v !== action.xxx));

    switch(action.type){
      case "ADD":
        return [...current_state, action.xxx];                    //현재 배열 복사 + 추가된 값
      case "DEL":
        return [current_state.filter((v,i) => v !== action.xxx)];  //현재 배열에서 추가된 값을 제외한 값
      default:
        return current_state;
    }
  };

  const [item, setItem] = useState("");
  const [items, dispatch] = useReducer(reducer, []);

  function handleChange(event){
    setItem(event.target.value);    //이벤트가 발생한 곳의 value
  }

  return(
    <>
      <UserContext.Provider value={[dispatch, item]}>
        <div>
          <input type="text" value={item} onChange={handleChange}></input>
          <Button></Button>
        </div>
        {items}
      </UserContext.Provider>
    </>
  )
}

 

Button
import { useContext } from "react"
import { UserContext } from "../App"

export default function Button(){

    const [dispatch, item] = useContext(UserContext);

    return (
        <>
            <button onClick={() => dispatch({type:"ADD", xxx: item})}>추가</button>    
            <button onClick={() => dispatch({type:"DEL", xxx: item})}>삭제</button>    
        </>
    )
}

 

'단순 코드 기록 > React' 카테고리의 다른 글

React_useEffect_addEventLister  (0) 2024.03.19
React_useEffect Hook  (0) 2024.03.19
React_Context(Single/Multi)  (0) 2024.03.18
React_useReducer_글자  (0) 2024.03.18
React_useReducer_숫자 증감  (0) 2024.03.18