簡體   English   中英

反應創建模態窗口的最佳實踐

[英]React best practice to create modal window

如何使用React創建模態窗口? 通過模態窗口,我的意思是一個覆蓋頁面內容的框架。 我希望它能夠使用網頁上的按鈕打開,能夠通過單擊外部區域來關閉它,它將包含一個用戶將填寫並提交的表單。

React是否為此任務提供了一些生產就緒庫,還是應該使用css實現它? 同樣在容器/代表性組件模式的情況下,我應該將模態組件嵌套在模態開口組件的容器組件內還是模態開口組件本身內?

React Modal是一個很棒的庫。

1 - 如果你想在React中編寫一個通用模態組件,你的反應模態組件應該做的唯一事情就是給出一致的視圖,例如包含疊加,設置定位值和所有常見行為等。交互決策取決於你如何繼續申請。 例如,我提到的這種方法(1),更適合使用Flux。 基本上你有一個商店,並收集其中的所有組件狀態相關數據,並且ui狀態由傳遞給你的組件的props管理,而不是調用setState來改變組件的狀態。 此外,這使您能夠在組件外部更改組件的狀態。 讓我用一個例子清楚自己:

import "./modal.scss";

class Modal extends React.Component {
  constructor(props) {
    super(props);
  }

  shouldComponentUpdate(nextProps) {
    return !I.is(this.props.data, nextProps.data);
  }

  render() {
    let isOpen = this.props.data.get("isOpen");
    return (
      <div className={`flex middle center modal ${isOpen ? "open" : ""}`}>
      {isOpen ?
        (<div className={`row modal-content ${this.props.size || ""}`}>
          <div className="col-12 middle modal-title">{this.props.title}</div>
          <div className="col-12 modal-body">
            {this.props.body}
          </div>
          <div className="col-12 middle modal-footer">{this.props.footer}</div>
        </div>) : null
      }
      </div>);
  }
}

export default Modal;

和樣式文件如:

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 10000;
  padding: 2rem;
  background-color: rgba(0, 0, 0, 0.55);

  .modal-content {
    background-color: white;
    max-height: 80%;
    height: 80%;

    .modal-title {
      padding: 0 2.25rem;
      height: 5rem;
      max-height: 5rem;
      text-transform: uppercase;
      font-size: 1.8rem;
    }

    .modal-body {
      height: calc(100% - 16rem);
      overflow-y: scroll;
      padding: 0 2rem;
    }

    .modal-footer {
      height: 5rem;
      max-height: 5rem;
      padding: 0 2.25rem;
    }
  }
}

你可以用它作為:

<Modal isOpen={/* depends on your parameter */} 
       title="Hello Title" 
       body="Hello Body"
       footer="Hello Footer"
/>

此模態設計僅提供模態的正確視圖和基本控件,配置完全取決於您的用法。 如果您的應用程序邏輯在其他模態用法中非常相似,那么您可以自己將它們添加到模態組件中。

暫無
暫無

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

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