UNPKG

kara-rc-web

Version:

kara项目react组件库

118 lines (105 loc) 2.96 kB
import React from 'react' import { string, oneOf, bool, func, shape, arrayOf } from 'prop-types' import classnames from 'classnames' import Icon from '../icon/icon' import Tooltip from '../tooltip/tooltip' class Dropdown extends React.Component { static propTypes = { prefixCls: string, className: string, children: arrayOf(shape({ label: string, })).isRequired, // [{value, label}]的形式 type: oneOf(['grey', 'white', 'orange']), // 颜色样式 size: oneOf(['', 'sm', 'default', 'md', 'lg']), // 大小 disabled: bool, // 下拉是否不可用 onClick: func, // 下拉选择项之后的回调函数 } static defaultProps = { type: 'orange', prefixCls: 'kara-dropdown', className: '', size: 'default', onClick: () => {}, disabled: false, style: {}, current: null, } state={ show: false, current: null, } componentDidMount() { document.body.addEventListener('click', this.closePopover, false) if (this.state.current === null) { // eslint-disable-next-line this.setState({ current: this.props.children[0] }) } } componentWillUnmount() { document.body.removeEventListener('click', this.closePopover) } openPopover = (e) => { if (!this.state.show && !this.props.disabled) { this.preventNextClose = true this.setState({ show: true }) } e.stopPropagation() } closePopover = () => { if (this.preventNextClose && this.state.show) { this.setState({ show: false }) } this.preventNextClose = false // 这个变量用在打开状态下点击下拉不关闭 } handleClick = (x, i) => { this.props.onClick(x, i) this.setState({ current: x }) } render() { const { prefixCls, type, className, size, children, } = this.props const classNames = classnames(prefixCls, { [`${prefixCls}-${type}`]: true, [`${prefixCls}-${size}`]: size, }, className) return (<div className={classNames} > <div className={`${this.state.show ? `${prefixCls}-br` : ''} ${prefixCls}-current`} onClick={this.openPopover} > <span>{ this.state.current && this.state.current.label}</span> {children.length > 1 ? (<Icon type="triangle-curve" className={`${prefixCls}-icon`} size="" />) : null} </div> {this.state.show ? (<div className={`${prefixCls}-ul`}>{ children.map((x, i) => (<Tooltip // eslint-disable-next-line key={`${i}${x.value}`} placement="top" title={x.label} > <div className={`${prefixCls}-li`} onMouseUp={(e) => { e.stopPropagation() this.handleClick(x, i) }} > {x.label} </div> </Tooltip>)) }</div>) : null} </div>) } } export default Dropdown