로우로우를 개발하면서
Main 페이지 안에 Ask 가 있고, Ask를 이루고있는 컴포넌트중 하나로 AskForm가 있을 때, AskForm에서 Main에 영향을 주는 방법이 필요했다!
props 를 통해 함수를 전달해서, 하위 하위 컴포넌트인 AskForm에서 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 컴포넌트
const Ask = ({ onQueryAction }) => {
return (
<Wrapper>
<Info />
<SituationBox title="예시" buttonName="다시시도" img_url={refresh} />
<AskForm onQueryAction={onQueryAction} /> {/* AskForm에 props로 전달 */}
</Wrapper>
);
};
// AskForm 컴포넌트
const AskForm = ({ onQueryAction }) => {
return (
<Wrapper>
<Button type="button" onClick={onQueryAction}></Button> {/* 버튼 클릭 시 onQueryAction 호출 */}
</Wrapper>
);
};