본문 바로가기
웹/react.js

Context 예제

by java개발자 2021. 3. 3.

Test.tsx

import React, {useContext} from 'react';
import ColorContext, {ColorProvider} from '../contexts/color';

const Update1 = () => {
  const { state, actions } = useContext(ColorContext);

  console.log('state', state);
  return (
    <div>
      state: {state.color}
      <br/>
      <button onClick={() => {
        actions.changeColor('hahah');
        actions.increase(123);
      }}>클릭</button>
    </div>
  )
}
const Select1 = () => {
  const { state, actions } = useContext(ColorContext);

  console.log('state', state);
  return (
    <div>
      Select1 color: {state.color}
      Select1 size: {state.size}
    </div>
  )
}

export default function Component() {
  const { state } = useContext(ColorContext);

  return (
    <div>
      <ColorProvider>
        <Update1 />
        <Select1 />
      </ColorProvider>
    </div>
  )
}

color.tsx

import React, { createContext, useState } from 'react'

const ColorContext = createContext({
  state: {
    color: 'balck',
    size: 12
  },
  actions: {
    changeColor: (a: string) => {
      console.log('changeColor default', a);
    },
    increase: (a: number) => {
      //
    }
  }
})
const ColorProvider = ({children}: {children: any}) => {
  const [state, setState] = useState({
    color: 'red',
    size: 30
  });
  const changeColor = (newColor: string) => {
    setState((prevState: any) => {
      return {
        ...prevState,
        color: newColor
      }
    })    
  }
  const increase = (newValue: number) => {
    setState((prevState: any) => {
      return {
        ...prevState,
        size: prevState.size + newValue
      }
    })
  }
  const value = {
    state,
    actions: {
      changeColor,
      increase
    }
  }
  return (
    <ColorContext.Provider value={value}>
      {children}
    </ColorContext.Provider>
  )
}

export {
  ColorProvider,
}
export default ColorContext