UNPKG

kara-rc-web

Version:

kara项目react组件库

65 lines (54 loc) 1.61 kB
import React from 'react' import classnames from 'classnames' import { string, number, func, oneOfType } from 'prop-types' import Icon from '../icon/icon' // 物品计数组件 class Count extends React.Component { static propTypes = { prefixCls: string, className: string, num: oneOfType([number, string]), onChange: func, // 数据发生变化回调函数 } static defaultProps = { prefixCls: 'kara-count', className: '', num: 0, onChange: () => {}, } state = { num: this.props.num, } onChange = (e) => { // 这个地方为空时 this.setState({ num: e.target.value }) this.props.onChange(Number(e.target.value)) } onBlur = (e) => { if (e.target.value === '') { this.setState({ num: 0 }) } } add = () => { const num = Number(this.state.num) + 1 this.setState({ num }) this.props.onChange(num) // 回调函数触发将变化后的数据返回 } minus = () => { const num = Number(this.state.num) - 1 if (num > 0) { this.setState({ num }) this.props.onChange(num) } } render() { const { prefixCls, className } = this.props const classNames = classnames(prefixCls, className) return (<div className={classNames}> <span className={`${prefixCls}-minus`} onClick={this.minus}><Icon type="minus" size="xs" /></span> <input type="number" value={this.state.num} onChange={this.onChange} onBlur={this.onBlur} /> <span className={`${prefixCls}-plus`} onClick={this.add}><Icon type="plus" size="xs" /></span> </div>) } } export default Count