真實經歷javascript
最近開發項目的時候,須要實現圖片的預覽並下載,想着也不難,本身寫一個預覽效果吧。其實預覽就是一個彈窗(Modal),實現彈窗有兩種方案:
一、使用es6的寫法,直接將彈窗和按鈕放在一塊兒,代碼大概以下:html
/* Img */ class RenderImg extends Component { state = { showModal: false, }; // 打開預覽 openModal = ()=>{ this.setState({ showModal: true }); } // 關閉預覽 closeModal = ()=>{ this.setState({ showModal: false }); } render(){ let {showModal} = this.state; let {text, url} = this.props; return ( <Fragment> <a href="javascript:;" onClick={this.openModal}>{text}</a> { showModal && <div className="modal-preview preview-image"> {/*somecode....*/} </div> } </Fragment> ); } }
這樣作的缺點是彈窗代碼不少,直接和按鈕放一塊兒,不太好。java
二、經過js建立dom,而後放到body的最下面,不少組件都是這麼寫的,代碼大概以下:react
/* 圖片類型 */ class RenderImage extends Component { //彈窗 _modal = null; // 打開預覽 openModal = ()=>{ this._modal = this.createModal(); this._modal.show(); } // 關閉預覽 closeModal = ()=>{ this._modal.hidden(); } // 下載 download = ()=>{ downloadFile(this.props.url) } //建立Modal createModal = ()=>{ let _this = this; return { _elem: null, //顯示 show: function(){ //此處是重點 }, //關閉 hidden: function(){ this._elem && this._elem.remove(); } }; } //建立元素 createElem = ()=>{ let {text, url} = this.props; return ( <div className="modal-preview preview-image"> {/*somecode...*/} </div> ); } render(){ let {text, url} = this.props; return <a href="javascript:;" onClick={this.openModal}>{text}</a>; } }
由於彈窗的內容比較多,因此建立彈窗代碼的時候使用了jsx,咱們知道jsx代碼不能直接經過appendChild放到建立的dom元素中,忽然靈光一閃,想到了很久不用的React基礎寫法ReactDOM.render(template, dom).es6
正片環節(ReactDOM.render)babel
若是咱們想在html文件中直接使用react,那咱們就要用到ReactDOM.render,做用就是將jsx代碼轉化爲HTML代碼,並插入指定的dom節點中,來一段簡單的代碼:app
<html> <head> <script src="http://static.runoob.com/assets/react/react-0.14.7/build/react.min.js"></script> <script src="http://static.runoob.com/assets/react/react-0.14.7/build/react-dom.min.js"></script> <script src="http://static.runoob.com/assets/react/browser.min.js"></script> </head> <body> <div id="app"></div> <script type="text/babel"> let userName = "Eric"; ReactDOM.render( <div>謝謝觀看{userName}的文章,喜歡就點贊轉發吧!</div>, document.getElementById("app") ); </script> </body> </html>
總結dom
若是想把jsx代碼轉化爲html代碼,就可使用ReactDOM.render,那麼上面的show方法咱們就能夠這麼寫:ui
show: function(){ this._elem = document.createElement("div"); ReactDOM.render(_this.createElem(), this._elem); document.body.appendChild( this._elem ); }
思考:圖片在自適應大小的狀況下,如何作到讓圖片水平和垂直居中顯示?this