basic/React.js
[React.js] history 객체 이용하기
ekgoddldi
2021. 2. 17. 22:26
props 안에는 history객체가 있고
그 안에는 goBack() 등이 있다.
따라서 props.history.goBack()을 통해 뒤로가기를 구현할 수 있다.
자세한것은 콘솔창에 props.history를 찍어보면 바로 알 수 있을 것이다.
props로 받지 않고 아래의 예시와 같이 history객체를 바로 받아올 수도 있다.
import React from "react";
function Comp({ history }) {
return (
<div>
<button onClick={() => history.push('/menu')}>Menu으로 이동</button>
</div>
);
}
export default Comp;
|
react-router-dom의 페이지 이동시 알림창을 띄우는 block을 이용해 보자
import React, { useEffect } from 'react'
function HistorySample({ history }) {
//뒤로 가기
const goBackHandler = () => {
history.goBack()
}
//'/'로 이동
const goHomeHandler = () => {
history.push('/')
}
useEffect(() => {
//이것을 설정하고 나면 페이지에 변화가 생기려고 할 때마다 정말 나갈 것인지를 질문함
const unblock = history.block('Are you sure?')
return () => {
//컴포넌트가 언마운트되면 질문을 멈춤
if (unblock) {
unblock()
}
}
}, [history])
return (
<div>
<button onClick={goBackHandler}>뒤로</button>
<button onClick={goHomeHandler}>홈으로</button>
</div>
)
}
export default HistorySample
|