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
'웹 > react.js' 카테고리의 다른 글
react-redux (0) | 2021.03.03 |
---|---|
onClick 대신 onMouseDown (0) | 2021.03.03 |
ie11에서 onMouseEnter가 중첩되었을때 event를 하위 컴포넌트까지 pass 하지 않음. (0) | 2021.03.03 |
onMouseEnter 이슈 (0) | 2021.03.03 |