React로 사용자 지정 확인 상자를 만드는 방법
20313 단어 reactwebdevtutorialjavascript
오늘 저는 사용자 지정 확인 상자를 만든 방법을 공유하고 싶었습니다. 표준 확인 상자는 브라우저마다 다소 지루하고 다르게 보이기 때문입니다.

예를 들어 동일한 확인 상자가 Firefox에서 다음과 같이 표시됩니다.

Chrome에서 이와 같이

예쁘지 않은. 이렇게 설정할 수 있습니다.
<button
className="delete button"
onClick={() => {
const confirmBox = window.confirm(
"Do you really want to delete this Crumb?"
)
if (confirmBox === true) {
handleDeleteCrumb(bookmark)
}
}}>
</button>
소개
맞춤 변형은 다음과 같이 작동합니다.
div
를 추가합니다div
안에 텍스트와 취소 및 확인 버튼을 추가합니다정상 상태에서 배경과 컨테이너는 모두
display: none
속성을 갖습니다. 즉, 화면에 표시되지 않으며 visibility: hidden
이외의 공간은 차지하지 않습니다.예를 들어 내 경우에는
display: none
를 display: flex
로 변경하는 함수를 호출하는(또는 none
가 아닌 다른 항목 대신) 버튼을 클릭하여 표시합니다.여러 가지 방법으로 표시할 수 있습니다.
display.querySelector(".container").style.display =
를 사용하여 상자display: none
.display: none
속성을 useState로 전환합니다display: flex
와 display: none
사이를 전환합니다.이 게시물에서는 첫 번째 변형에 중점을 둘 것입니다. 관심이 있으시면 다른 방법에 대한 후속 조치도 할 수 있습니다. 댓글로 알려주세요.
요소 만들기
먼저 배경을 만들어 봅시다. 상자 외부 아무 곳이나 클릭하여 상자를 닫을 수 있도록 추가하고 있습니다. 또한 배경이 보이는 동안
overflow:hidden
로 스크롤을 비활성화합니다. 확인 상자를 강조하기 위해 검정색과 50% 불투명도로 만들고 싶지만 완전히 불투명하게 만들 수도 있습니다./* The JSX */
<>
<div
className="confirm-bg"
onClick={() => handleConfirmationBox()}>
</div>
</>
/* The CSS */
.confirm-bg {
position: fixed;
display: none;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: #202020;
opacity: 0.55;
overflow: hidden; /* disable scrolling*/
z-index: 2; /* higher than all other items, but lower than
the confirm box*/
}
다음으로 컨테이너를 추가합니다.
position: fixed
를 사용하여 삭제 버튼 가까이에 배치합니다. 구성 요소에서 배경 바로 앞에 추가해야 합니다. 그렇지 않으면 화면에서 배경 뒤에 나타납니다./* The JSX */
<>
<div className="container">
<div className="confirmation-text">
Do you really want to delete this task?
</div>
<div className="button-container">
<button
className="cancel-button"
onClick={() => handleConfirmationBox()}>
Cancel
</button>
<button
className="confirmation-button"
onClick={handleDeleteTask}>
Delete
</button>
</div>
</div>
<div
className="confirm-bg">
onClick={() => handleConfirmationBox()}
</div>
</>
/* The CSS */
.container {
display: none;
flex-direction: column;
position: fixed;
background-color: #f37736;
width: 230px;
top: 75%;
left: 50%;
transform: translate(-50%, -75%);
border-radius: 0.3rem;
padding: 1rem;
z-index: 5; /* Higher than the z-index of the background */
}
.confirmation-text {
display: flex;
color: white;
margin: 0.5rem 0 2rem;
text-align: center;
line-height: 2rem;
font-size: 1.1rem;
}
.button-container {
display: flex;
margin-top: auto;
justify-content: space-between;
}
.confirmation-button, delete-button {
display: inline-flex;
background-color: #cc0000;
color: white;
padding: 0.7rem 1.4rem;
border: none;
border-radius: 0.3rem;
font-size: 1rem;
}
.cancel-button {
background-color: #999999;
}
.confirmation-button:hover {
background-color: red;
cursor: pointer;
}
.cancel-button:hover {
background-color: #b2b2b2;
cursor: pointer;
}
요소 전환
이제 요소가 설정되었으며 요소를 표시하고 다시 숨길 수 있습니다.
먼저 확인 확인을 트리거하는 버튼이 필요합니다. 구성 요소의 어느 위치에나 있을 수 있습니다. 클릭하면 버튼이
display
속성을 변경하는 함수를 호출합니다./* JSX */
<button
className="delete-button"
onClick={() => {handleConfirmationBox()}>
Delete
</button>
handleConfirmationBox
내부에서 state
를 사용하여 확인 확인을 표시할지 숨길지 확인합니다. 부울 값을 사용하고 기본값을 false로 설정합니다. handleConfirmationBox 함수에서 팝업 숨기기에 false를 할당합니다.다음과 같은 경우 이 함수를 호출합니다.
/* define the state */
import { useState } from "react"
const [delTask, setDelTask] = useState(false)
/* if delTask is false, change the display properties of our
* two elements and change delTask to true, so that next time
* the function is called, the elements are hidden again
*/
const handleConfirmationBox = () => {
if (!delTask) {
document.querySelector(".confirm-bg").style.display = "flex"
document.querySelector(".container").style.display = "flex"
setDelTask(true)
} else {
document.querySelector(".confirm-bg").style.display = "none"
document.querySelector(".container").style.display = "none"
setDelTask(false)
}
최종 단어
그리고 그게 다야. 이제 확인은 모든 장치에서 동일하게 표시되며 원하는 방식으로 사용자 지정할 수 있습니다. 내가 말했듯이 숨기기/숨기기 해제를 수행하는 방법에는 여러 가지가 있습니다. 저는 개인적으로
delTask
상태를 prop으로 전달하고 이를 기반으로 display
속성을 변경할 수 있기 때문에 스타일이 지정된 구성 요소를 좋아합니다.궁금한 점이 있거나 놓친 것이 있으면 알려주세요.
Reference
이 문제에 관하여(React로 사용자 지정 확인 상자를 만드는 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/isarisariver/how-to-create-a-custom-confirm-box-with-react-754텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)