모바일 APP/React-Native
자식 컴포넌트 -> 부모 컴포넌트 상태 변경하기
살길바라냐
2021. 7. 16. 00:54
반응형
부모 컴포넌트 state상태와 setState 함수를 자식 컴퍼넌트에 넘겨준다.
/* 부모 컴포넌트 */
import React, {useState} from 'react'
import type {FC} from 'react'
/* 자식 컴포넌트 불러오기*/
import Child from './Child'
// 속성 타입 정의
export type Props = {
state: D.state
}
const Parent : FC<Props> = ({state: initialState}) => {
// 부모 useState 훅 정의
const [state, setState] = useState<D.state>({
...initialState,
counts: {comment: 0, retweet:0, heart: 0}
})
// 자식 컴포넌트
<Child state={state} setState={setState}/>
}
setter 함수 타입 만들어서 부모 컴포넌트에 업데이트된 상태 반환한다.
/*자식 컴포넌트*/
import React, {useCallback} from 'react'
import type {FC} from 'react'
// setter 타입 정의
export type childProps = {
state: D.State
setState: Dispatch<SetStateAction<D.State>>
}
const Child: FC<childProps> = ({state, setState}) => {
const comment = useCallback(
()=> setState((state)=> {...state, comment: comment + 1})
,[])
const retweet = useCallback(
()=> setState((state)=> {...state, retweet: retweet + 1})
,[])
const heart = useCallback(
()=> setState((state)=> {...state, retweet: retweet + 1})
,[])
return (...)
}
728x90