하위 컴포넌트에서 상위 컴포넌트에 영향을 주고 싶을 때 - 함수 props 전달

JeongInHuh·2024년 4월 5일

React

목록 보기
5/6

로우로우를 개발하면서
Main 페이지 안에 Ask 가 있고, Ask를 이루고있는 컴포넌트중 하나로 AskForm가 있을 때, AskForm에서 Main에 영향을 주는 방법이 필요했다!

props 를 통해 함수를 전달해서, 하위 하위 컴포넌트인 AskForm에서 Main 페이지를 조작할 수 있다!

Main 컴포넌트

// 메인페이지
import React, { useState } from 'react';
import Ask from './Ask';
import Result from './Result';

function Main() {
  const [isResultVisible, setIsResultVisible] = useState(false);

  const handleQueryAction = () => {
    // 버튼 클릭 시 실행될 함수
    setIsResultVisible(true);
  };

  return (
    <div>
      {isResultVisible ? <Result /> : <Ask onQueryAction={handleQueryAction} />}
    </div>
  );
}

export default Main;

Ask 컴포넌트

// Ask 컴포넌트
const Ask = ({ onQueryAction }) => {
  return (
    <Wrapper>
      <Info />
      
      <SituationBox title="예시" buttonName="다시시도" img_url={refresh} />
      
      <AskForm onQueryAction={onQueryAction} /> {/* AskForm에 props로 전달 */}
    </Wrapper>
  );
};

AskForm 컴포넌트

// AskForm 컴포넌트
const AskForm = ({ onQueryAction }) => {
 return (
    <Wrapper>
        <Button type="button" onClick={onQueryAction}></Button> {/* 버튼 클릭 시 onQueryAction 호출 */}
    </Wrapper>
  );
};
profile
신입개발자. 이젠 서버를 곁들인 velog 꾸미기 : https://velog.io/@ybkim3603/Velog벨로그-사용법-튜토리얼 Git컨벤션: https://velog.io/@shin6403/Git-git-커밋-컨벤션-설정하기 커리어 방향 설정 모음글:https://velog.io/@eon7500/커리어-방향성-설정에-도움되는-글

0개의 댓글