UNPKG

kara-rc-web

Version:

kara项目react组件库

87 lines (78 loc) 2.26 kB
import React from 'react' import { string, oneOf, bool, func, any, shape } from 'prop-types' import classnames from 'classnames' import alarmImg from './alarm.png' // 受控组件 class Inputrc extends React.Component { static propTypes = { prefixCls: string, className: string, color: oneOf(['grey']), // 颜色样式 size: oneOf(['sm', 'default']), // 输入框大小 disabled: bool, // 输入框是否不可用 onChange: func, // onClick事件回调函数, onChange事件需要把使用props传过来的value值更改 type: string, // 输入框类型 placeholder: string, // eslint-disable-next-line value: any, rule: shape({ // 规则对象,靠安排适当的正则表达式控制alarm提示的出现 text: string, reg: string, }), } static defaultProps = { type: 'text', placeholder: '', prefixCls: 'kara-inputrc', className: '', color: 'grey', size: 'default', onChange: () => {}, disabled: false, style: {}, value: '', rule: { text: '', reg: '', }, } state = { focus: false, isValid: false, } onFocus = () => { this.setState({ focus: true }) } onBlur = () => { this.setState({ focus: false }) } onReg = (value) => { const reg = new RegExp(this.props.rule.reg) this.setState({ isValid: reg.test(value) }) } render() { const { prefixCls, type, className, size, color, onChange, disabled, rule, placeholder, value } = this.props const classNames = classnames(prefixCls, { [`${prefixCls}-${color}`]: true, [`${prefixCls}-focus`]: this.state.focus, [`${prefixCls}-${size}`]: size, }, className) return (<div className={classNames}> <input type={type} value={value} placeholder={placeholder} onChange={(e) => { if (!disabled) { onChange(e) this.onReg(e.target.value) } }} onFocus={this.onFocus} onBlur={this.onBlur} /> {!disabled && this.state.isValid ? null : (<span className={`${prefixCls}-alarm`} > <img src={alarmImg} alt="⚠️" /> <span>{rule.text}</span> </span>)} </div>) } } export default Inputrc