[TIL] 상위 컴포넌트에서 함수 제어하기

JIEUN YANG·2024년 4월 16일
0

리액트 컴포넌트는 상위,하위 모듈 간 데이터 통신을 할 때 Props라는 개념이 존재한다.
Props는 변수, 함수, 컴포넌트가 될 수 있으며 그 중 함수를 전달하고 사용하는 방법을 알아보자.

// custom component

import { Option } from './select.ts' 

type Props = { 
    options : Option[], // options Props는 Option 타입의 배열형태로 데이터를 전달한다.
    onChecked? : Function, // onChecked Props는 Function 타입 데이터를 주고 받는다
    value : string | number // value Props는 string 혹은 number 타입의 데이터를 전달 받는다.
}

export default function JwtSelect({options, onChecked, value} : Props) {

    const handleOnChecked = (currentvalue : any) => {
        if(onChecked) onChecked(currentvalue)
    }

    return (
        options.map((option : Option) => 
        <div>
            {option.name}
        <input type="checkbox" checked={value === option.value} onClick={handleOnChecked(option.value)}/>
        </div>
        )
 )
}

// layout.tsx
export default function Layout() {
  
  	const [value, setValue] = useState<string | number(0)

    const handleCheck = (currentValue : string | number) => {    
    setCheckValue(currentValue)
  }

  const testOptions = [
    {name : '나는 나는 저팔계', value : '왜 나를 싫어하나'},
    {name : '나는 사오정', value : '나방나온다아아아'} ]
}

return (
	<>
<JwtSelect options={testOptions} value={value} onChecked={handleCheck}/>
	</>
}

두 개의 컴포넌트가 'layout' <-> 'custom component' 통신을 할 때, options의 Props로 데이터를 넘겨주듯, 하위 컴포넌트(custom component)에서 onChecked로 전파된 함수형 props는 상위 컴포넌트(layout)에서 'handleCheck'라는 이름을 가진 함수로 재정의된다.
handleCheck함수로 Props 함수를 재정의하지 않는다면 하위컴포넌트에서 정의만 하고 상위 컴포넌트에서는 아무런 이벤트가 발생하지 않는다. 즉, handleCheck 로 재정의된 함수가 해당 컴포넌트(layout)에서 수행할 동작들을 제어한다.

profile
violet's development note

0개의 댓글