Dropdown.js 2.8 KB
import React,{PropTypes} from 'react';  
import cx from 'classnames';
import s from './Dropdown.scss';



class Dropdown extends React.Component {
	constructor(props) {
        super(props);  
        this.mouseOnFlag=this.mouseOnFlag.bind(this);
        this.mouseOutFlag=this.mouseOutFlag.bind(this);
        this.triggerCloseMenu=this.triggerCloseMenu.bind(this);
        this.showMenu=this.showMenu.bind(this);
        this.state={
			showMenu:false,
			showMenuItem:false,
			closeFlag:false,
			showItemKey:''
        }
    }
    static propTypes = {  
    	resource: PropTypes.object.isRequired,
		children: PropTypes.element,
		showMenu:PropTypes.bool.isRequired,
		options:PropTypes.array.isRequired,
		menuWidth:PropTypes.number.isRequired,
		detailWidth:PropTypes.number.isRequired,
		detailHeight:PropTypes.number.isRequired,
		onChange:PropTypes.func.isRequired
	} 
	static defaultProps={
		showMenu:false,
		menuWidth:160,
		detailWidth:300,
		detailHeight:320
	}
	mouseOutFlag(){
		this.setState({
			closeFlag:true
		})
	}
	mouseOnFlag(){
		this.setState({
			closeFlag:false
		})
	} 
	overMenu(fixType,e){ 
		this.setState({
			showMenuItem:true,
			showItemKey:fixType
		});
		this.props.onChange(fixType);
	}
	triggerCloseMenu(){
		if(this.state.closeFlag){
			this.setState({
				showMenu:false,
				showMenuItem:false
			});
		}
	}
	showMenu(){
		this.setState({
			showMenu:true
		});
	}
	componentDidMount(){ 
	    window.addEventListener('mousedown', this.triggerCloseMenu); 
	}
	componentWillUnmount() { 
	   window.removeEventListener('mousedown', this.triggerCloseMenu); 
	}
	menu(){
		const {showMenuItem}=this.state;
		const {menuWidth,detailWidth,detailHeight}=this.props;
		const menuItemDetailStyle={
			right:`${menuWidth}px`,
			minWidth:`${detailWidth}px`,
			minHeight:`${detailHeight}px`,
			top:`-${detailHeight/2}px`
		};
		return (
			<div style={menuItemDetailStyle} className={cx(s.menu_item_body_wrap,showMenuItem?s.show:'')}>
				{this.props.children}
			</div>
		)	
	}
	render(){
		const self=this;
		const {showMenu,showMenuItem,showItemKey}=this.state;
		const {resource,options,menuWidth}=this.props;
		const menuItemStyle={minWidth:`${menuWidth}px`};
		return (
			<div className={cx(s.dropdown_wrap)}> 
				<div className={cx(s.show_btn_wrap)}>
					<a href="javascript:;" onClick={this.showMenu}>查看</a>
				</div>
				<ul style={menuItemStyle} className={cx(s.dropdown_menu,showMenu?s.show:'')} onMouseOver={this.mouseOnFlag} onMouseOut={this.mouseOutFlag}>
					{options.map((fixType,_index)=>{
						return(
							<li  key = {_index}>
								<a className={cx(s.menu_item_wrap)} href="javascript:;"  onMouseOver={self.overMenu.bind(self,fixType)}>{resource[fixType]}</a>
								{showMenuItem&&showItemKey==fixType?this.menu():''} 
							</li>
						)
					})}
				</ul> 
			</div>
		)
	}
}


export default Dropdown;