UNPKG

lm-form

Version:

* 作者:liuduan * 邮箱:liuduan.05.05@163.com * 版本:**`1.0.2`**

126 lines (108 loc) 4.41 kB
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import {Cell, CellBody, Label} from "lm-cell"; import emitter from './events'; import './index.scss'; // 识别每个input实例的唯一id。 let id = 0; const InputValidateHoc = Input => { return class InputValidate extends Component { static propTypes = { hintClassName: PropTypes.string, // hint自定义类名 value: PropTypes.oneOfType([ // 值,配合onChange使用 PropTypes.string, PropTypes.number ]), validate: PropTypes.object, // 验证参数配置 required: PropTypes.bool, // 是否必填 onChange: PropTypes.func, // onchange事件回调 onFocus: PropTypes.func, // onfocus事件回调 onBlur: PropTypes.func, // onblur事件回调 label: PropTypes.string // label左侧文案 }; static defaultProps = { validate: {}, required: false, onChange() { }, onFocus() { }, onBlur() { }, label: '' }; constructor(props) { super(props); this.state = { hintShow: false, err: false, message: '' }; this.handleErrState = this.handleErrState.bind(this); } id = id++; componentDidMount() { this.props.validate.type === "submitValidate" && emitter.on('inputErrEvent', this.handleErrState); } componentWillUnmount() { this.props.validate.type === "submitValidate" && emitter.removeListener('inputErrEvent', this.handleErrState) } handleErrState(param) { if (param.id === this.id) { this.setState({ err: true }); } } // 验证值 validateValue = (value) => { const { validate, required } = this.props; return this.props.inputValidate({ value, ...validate, required }); } // 失焦处理 下划线变红 下面红字提示 handleBlur = value => { const { onBlur, validate: {type} } = this.props; const { isValid, message } = this.validateValue(value); // 验证不通过 if (!isValid && type !== "submitValidate") { // 下划线变红 并展示错误提示 this.setState({ hintShow: true, err: true, message }); } // 将验证信息发送出去--->Form接收 emitter.emit('validateEvent', { id: this.id }, { isValid, message, name: this.props.name, value, type }); // 触发回调 onBlur(value, { isValid, message }); } // focus时 干掉错误提示 handleFocus = value => { const { onFocus, validate: {type} } = this.props; // 如果有错误提示时 干掉错误提示 if (this.state.hintShow && type !== "submitValidate") { this.setState({ hintShow: false, err: false }); } // 触发回调 onFocus(value); } // 输入框变化 handleChange = value => this.props.onChange(value); render() { const { hintClassName, inputValidate, onChange, onFocus, onBlur, validate, required, err, onlySubmitValidate, label, ...others } = this.props; let { hintShow, message } = this.state; if (message === 'required') message = validate.requireMsg || '该字段不能为空'; return <div className={`lm-valid ${hintShow ? 'err' : ''}`}> <Cell> {label ? <Label>{label}</Label> : null} <CellBody> <Input err={this.state.err} onBlur={this.handleBlur} onFocus={this.handleFocus} onChange={this.handleChange} {...others}></Input> </CellBody> </Cell> {hintShow ? <div className="lm-valid-hint">{message}</div> : null} </div> } } } export default InputValidateHoc;