如何將jsx代碼放到自定義的dom中? - Eric
真實經歷
最近開發項目的時候,需要實現圖片的預覽並下載,想着也不難,自己寫一個預覽效果吧。其實預覽就是一個彈窗(Modal),實現彈窗有兩種方案:
1、使用es6的寫法,直接將彈窗和按鈕放在一起,代碼大概如下:
/* 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>
);
}
}
這樣做的缺點是彈窗代碼很多,直接和按鈕放一起,不太好。
2、通過js創建dom,然後放到body的最下面,很多組件都是這麼寫的,代碼大概如下:
/* 圖片類型 */
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).
正片環節(ReactDOM.render)
如果我們想在html文件中直接使用react,那我們就要用到ReactDOM.render,作用就是將jsx代碼轉化爲HTML代碼,並插入指定的dom節點中,來一段簡單的代碼:
<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>
總結
如果想把jsx代碼轉化爲html代碼,就可以使用ReactDOM.render,那麼上面的show方法我們就可以這麼寫:
show: function(){
this._elem = document.createElement("div");
ReactDOM.render(_this.createElem(), this._elem);
document.body.appendChild( this._elem );
}
思考:圖片在自適應大小的情況下,如何做到讓圖片水平和垂直居中顯示?