手把手教你實現一個modal對話方塊
阿新 • • 發佈:2018-12-21
需求: 1、點選一個按鈕彈出對話方塊 2、對話方塊的事件能夠被父元件捕捉 3、對話方塊裡的內容能夠隨時改變 一、如何實現一個對話方塊 1.1 建立一個簡單的對話方塊 簡而言之,一個簡單的對話方塊就是一個div(也可能是幾個div),怎麼建立呢?
function createModal () { //建立一個div var modalDiv = document.createElement('div'); // 給div加點內容 var modalText=document.createTextNode("這是對話方塊"); modalDiv.appendChild(modalText); // 給div加點樣式,給他放在頁面中間 modalDiv.style.position = 'absolute'; modalDiv.style.width = '400px'; modalDiv.style.height = '400px'; modalDiv.style.left = 0; modalDiv.style.right = 0; modalDiv.style.top = 0; modalDiv.style.bottom = 0; modalDiv.style.margin = 'auto'; modalDiv.style.backgroundColor = 'grey'; // 把div放到頁面中 document.body.appendChild(modalDiv); } // 建立一個按鈕觸發這個事件,如果你比較懶,可以把createModal中的內容copy到console中,就可以看到對話方塊了 <button type="button" onclick = 'createModal()'>點選我出現一個Modal</button>
1.2 建立一個優雅的對話方塊 像上面那樣就建立了一個對話方塊了,但是優雅嗎?No!!!,很醜陋,所以我們需要加幾點進去,讓它實現的更優雅:
- 新增過渡效果,對話方塊彈出的時候,應該讓它變得更加優雅
- 新增對話方塊的關閉按鈕,因為我們在body中添加了一個div,關閉需要刪除
- 一個對話方塊還需要這樣幾個要素
- 對話方塊的title
- 對話方塊的內容content
- 對話方塊的操作按鈕,關閉左上角或者右上角,以及自定義按鈕 本小節就不詳細說明後面會說到,如果你現在自己手動實現了,後面會更好理解
二、對話方塊的實現React元件 現在呢,都流行面向元件的程式設計,像上述的直接操作DOM不流行啦,如果說自己不能封裝一個元件,那你就out了,趕緊去封一個(手動狗頭)。不會麼?手把手教你啊。 要封裝一個元件要怎麼做來?需要哪幾個要素?
- 樣式
- 功能
- 靈活
- 編碼清晰
Show U my Code React 元件程式碼
import React , { Component } from 'react'; import ReactDOM from 'react-dom'; class Modal extends Component { static defaultProps = { modalStyle: { display: 'flex', flexDirection: 'column', width: '100%', height: '100%' }, titleStyle: { border: '1px solid red', height: '20%', width: '100%' }, contentStyle: { border: '1px solid blue', height: '60%', width: '100%' }, buttonStyle: { border: '1px solid pink', height: '20%', width: '100%' } } render () { const { title, content, buttons } = this.props; const { modalStyle, titleStyle, contentStyle, buttonStyle} = this.props; return (<div style = { modalStyle }> <div style = { titleStyle }> { title } </div> <div style = { contentStyle }> { content } </div> <div style = { buttonStyle }> { buttons } </div> </div>) } } export default class WrapModal extends Component { render() { const { visible } = this.props; if (!visible) { const noModal = document.getElementById('modal'); noModal && document.body.removeChild(noModal); return null; } var modalDiv = document.createElement('div'); modalDiv.id = 'modal'; modalDiv.style.position = 'absolute'; modalDiv.style.width = '400px'; modalDiv.style.height = '400px'; modalDiv.style.left = 0; modalDiv.style.right = 0; modalDiv.style.top = 0; modalDiv.style.bottom = 0; modalDiv.style.margin = 'auto'; modalDiv.style.backgroundColor = 'white'; document.body.appendChild(modalDiv); const modal = ReactDOM.render(<Modal {...this.props}/>, modalDiv); return modal; } }
好吧,我承認,上面的這個元件賊jb爛,遠遠沒有達到相應的需求,我的目的就是告訴你,他是怎麼來的,不負責他是怎麼變好的。