over 3 years ago

練習製作一個簡單的遮罩視窗 Component
內容如下

import React, {Component, PropTypes} from 'react'

class PopUp extends Component {
  constructor(props) {
    super(props);
    this.showPopUp = this.showPopUp.bind(this);
    this.resizePopUP = this.resizePopUP.bind(this);
    this.closePopUp = this.closePopUp.bind(this);
  }
  showPopUp() {
      this.refs.div.style.display = "block";
      this.refs.box.style.display = "inline-block";
      this.resizePopUP();
      window.addEventListener('resize', this.resizePopUP);
  }
  resizePopUP() {
      let box = this.refs.box;
      var boxWidth = box.offsetWidth;
      var boxheight = box.offsetHeight;

      box.style.zIndex = 100;
      box.style.position = "absolute";
      box.style.left = (window.innerWidth - boxWidth) / 2 + "px";
      box.style.top = (window.innerHeight - boxheight) / 2+ "px";
  }
  closePopUp() {
     this.refs.div.style.display = "none";
     this.refs.box.style.display = "none";
     window.removeEventListener('resize', this.resizePopUP);
  }
  render() {
    let divStyle = {"position":"absolute","display":"none","width":"100%","height":"100%","background-color":"#999999","left":"0px","top":"0px","opacity": "0.50","filter": "alpha(opacity=50)"};
    let boxStyle = {"display":"none"};
    return (
      <div>
      <div ref="div" style={divStyle} onClick={this.closePopUp}></div>
          <div ref="box" style={boxStyle}>
              {this.props.children}
          </div>
      </div>
    );
  }
}

export default PopUp

使用方式

包覆所要顯示的物件
這邊綁定了兩組 PopUp Component 採用 ref 做識別控制

可於主 View 呼叫 this.refs.PopUp2.showPopUp() 來顯示遮罩視窗
如 onClick={this.showBoxOne.bind(this)} 配置
點選遮罩可以關閉視窗
視窗會隨著畫面大小做置中變動

import React from 'react';
import ReactDOM from 'react-dom';
import PopUp from './Component/PopUp';
import ImgMask from './Component/imgMask';

class AppWrapper extends React.Component {
  constructor(props) {
    super(props)
  }
  showBoxTwo() {
    this.refs.PopUp2.showPopUp();
  }
  showBoxOne() {
    this.refs.PopUp.showPopUp();
  }
  render() {
    return(
      <div>
        <PopUp ref="PopUp">
          <div style={{"width":"150px","height":"180px","background-color":"white"}}>
          123
          465
          789
          </div>
        </PopUp>
        <input type="button" value="showBox" onClick={this.showBoxOne.bind(this)} />
        <PopUp ref="PopUp2">
        <ImgMask src="images/test.png" rectRadius={25} imgHeight={400} rectHeight={350}  rectWidth={250} />
        </PopUp>
        <input type="button" value="showBox2" onClick={this.showBoxTwo.bind(this)} />
      </div>
    )
  }
}
ReactDOM.render(<AppWrapper  />, document.getElementById('demo'))

效果


← 使用 Immutable 優化 React 簡易的使用 react-router-redux 建構 Redux 與 React Router 環境 →
 
comments powered by Disqus