over 3 years ago

練習一下 React Component 的編寫

圖片遮罩 component

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

class ImgMask extends Component {
  constructor(props) {
    super(props)
    this._onLoad =  this._onLoad.bind(this);
  }
  _onLoad() {
    let imgDom = this.refs.imgDom;
    let range = imgDom.naturalHeight / this.props.imgHeight;
    let imgW = imgDom.naturalWidth / range;
    let imgH = imgDom.naturalHeight / range;
    let imgTop = (this.props.rectHeight - imgH) / 2;
    let imgLeft = (this.props.rectWidth - imgW) / 2;
    imgDom.style.top = imgTop + 'px';
    imgDom.style.left = imgLeft + 'px';
    imgDom.style.position = 'absolute';
  }
  render() {
    let divStyle = {"position" : "relative",
                    "overflow" : "hidden",
                    "width" : this.props.rectWidth,
                    "height" : this.props.rectHeight,
                    "display" : (this.props.isInlineBlock) ? "inline-block" : "block",
                    "borderRadius": this.props.rectRadius,
                    "borderStyle" : "solid",
                    "borderWidth" : this.props.borderWidth};
    return (
      <div style={divStyle}>
        <img ref="imgDom" src={this.props.src} onLoad={this._onLoad} height={this.props.imgHeight} />
      </div>
    );
  }
}

ImgMask.defaultProps  = {
  rectHeight: 200,
  rectWidth: 200,
  isInlineBlock:true,
  rectRadius: 20,
  borderWidth: 0,
  imgHeight: 275
}

ImgMask.propTypes = {
  rectHeight: PropTypes.number.isRequired,
  rectWidth: PropTypes.number.isRequired,
  isInlineBlock:PropTypes.bool.isRequired,
  rectRadius: PropTypes.number.isRequired,
  borderWidth: PropTypes.number.isRequired,
  imgHeight: PropTypes.number.isRequired,
  src: React.PropTypes.string.isRequired
}

export default ImgMask

使用方式

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

class Main extends React.Component {
  render() {
    return (  
             <div>
                  <ul style={{display:"inline"}}>
                    <li><ImgMask src="images/test.png" rectRadius={50} /></li>
                    <li>
                      <ImgMask src="images/test.png" rectRadius={25} 
                        imgHeight={400} rectHeight={350}  rectWidth={250} />
                    </li>
                    <li><ImgMask src="images/test.png" rectRadius={10} borderWidth={5}  /></li>
                  </ul>
             </div>
           );
  }
}

ReactDOM.render(<Main  />, document.getElementById('img'))

效果

← React Stateless components 使用 Immutable 優化 React →
 
comments powered by Disqus