簡體   English   中英

如何在創建為樣式組件的自定義React模式中檢測onClickOutside和onEscapeKeyPress

[英]How to detect `onClickOutside` and `onEscapeKeyPress` in custom React modal created as a styled component

現在,我在此上花費了大量時間。 但是,由於無法使用樣式組件 ,因此我無法弄清楚。

我已經在React中創建了一個Modal風格的組件。 剩下要做的唯一事情就是添加“ onClickOutside”和“ onEscapeKeyPress”功能。

但是,對於我一生來說,我無法將事件偵聽器添加到Modal元素(也不能添加到基礎div元素)。

這是codeandbox演示的鏈接

這是我希望用戶使用我的組件的理想方式:

<Modal
    show={this.state.isOpen}
    onBackgroundClick={this.toggleModal}
    onEscapeKeydown={this.toggleModal}
    >
    <Modal.Wrapper>
        <Modal.Header>
            <!-- ignore this -->
        </Modal.Header>
        <Modal.Body>
            <!-- ignore this -->
        </Modal.Body>
        <Modal.Footer>
            <!-- ignore this -->
        </Modal.Footer>
    </Modal.Wrapper>
</Modal>

要么

<Modal
    show={this.state.isOpen}
    closeOnEscape
    closeOnClickOutside
    >
    <Modal.Wrapper>
        <Modal.Header>
            <!-- ignore this -->
        </Modal.Header>
        <Modal.Body>
            <!-- ignore this -->
        </Modal.Body>
        <Modal.Footer>
            <!-- ignore this -->
        </Modal.Footer>
    </Modal.Wrapper>
</Modal>

非常感謝您的幫助。

在等待SO社區的幫助時,我設法自己找到了解決方案。

簡而言之,對於像我這樣使用樣式組件的人還比較陌生的人:樣式組件就是那個,“樣式”組件。 您不能使用任何腳本重載它。 為了檢測onClickOutsideonEscapePress ,我不得不創建一個新的包裝器Modal組件, StyledModal組件在StyledModal使用StyledModal組件。 檢測按鍵和鼠標按下的代碼就位於此處。

以下是一些代碼片段來說明我的方法:

Modal.js (代碼段)

componentDidMount() {
  this.props.closeOnClickOutside &&
    document.addEventListener("mousedown", this.handleClick, false);
  this.props.closeOnEscape &&
    document.addEventListener("keyup", this.handleKeyPress, false);
}
render() {
  return (
    <StyledModal
      style={{ display: this.props.show ? "block" : "none" }}
      ref={this.modal}
    >
      <Wrapper>{this.props.children}</Wrapper>
    </StyledModal>
  );
}

StyledModal.jsx

import styled from "styled-components";

const StyledModal = styled.div`
  position: fixed;
  padding: 0;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100vh;
  background-color: grey;
  z-index: 1;
`;

export default StyledModal;

index.js (預期用途)

<Modal
  show={this.state.isOpen}
  closeOnEscape
  onClose={() => this.setState({ isOpen: false })}
>
  <Header>I have a nice title</Header>
  <Body>But not much to say...</Body>
  <Footer>
    <button onClick={this.toggleModal}>Cancel</button>
    <button onClick={this.toggleModal}>OK</button>
  </Footer>
</Modal>

工作演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM