728x90
App
import { useRef} from "react"
import Box from "./components/box"
export default function App(){
const boxRef = useRef();
function handleEvent(){
console.log("부모창에서 자식창의 open함수 호출")
boxRef.current.open(); //자식의 open함수 호출
}
return (
<>
<h1>App</h1>
<button onClick={handleEvent}>자식의 open 호출</button>
<Box ref={boxRef}>모달창 보기</Box>
</>
)
}
box
import { useRef, useImperativeHandle, forwardRef } from "react"
//반드시 fowardRef로 감싸고 Ref로 받음
const Box = forwardRef((props, ref) => {
const modal = useRef();
useImperativeHandle(ref, () => ({open})); //부모에게 노출
function open(){ //부모가 호출할 함수
modal.current.showModal(); //모달창 띄우기
}
const handleClose = () => {
modal.current.close();
};
return(
<>
<dialog ref={modal}> {/* 모달창 시작 */}
<h2>모달창</h2>
<form>
아이디: <input></input>
비밀번호: <input></input>
<button onClick={handleClose}>저장</button>
</form>
</dialog> {/* 모달창 끝 */}
</>
)
})//forwardRef
export default Box;
'단순 코드 기록 > React' 카테고리의 다른 글
React_부모창에서 자식창의 함수 불러오기 (0) | 2024.03.18 |
---|---|
React_속성으로 함수 사용 (0) | 2024.03.18 |
React_부모창에서 자식창의 함수 불러오기 (0) | 2024.03.15 |
React_조건부 랜더링, useRef (0) | 2024.03.15 |
React_Select 숫자 증감 (0) | 2024.03.15 |