lm-form
Version:
* 作者:liuduan * 邮箱:liuduan.05.05@163.com * 版本:**`1.0.2`**
99 lines (84 loc) • 2.86 kB
JavaScript
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Button from 'lm-button';
import emitter from './events';
import './index.scss';
export default class Submit extends Component {
static propTypes = {
className: PropTypes.string,
style: PropTypes.object,
type: PropTypes.string,
disabled: PropTypes.bool,
onClick: PropTypes.func,
onError: PropTypes.func
};
static defaultProps = {
disabled: true,
type: "",
onClick() { },
onError() { }
};
constructor(props) {
super(props);
this.state = {
validateMap: []
};
this.validateEventListener = this.validateEventListener.bind(this);
this.onClick = this.onClick.bind(this);
this.timer = null;
}
componentDidMount() {
emitter.on('validateEvent', this.validateEventListener);
}
componentWillUnmount() {
emitter.removeListener('validateEvent', this.validateEventListener)
clearTimeout(this.timer);
}
validateEventListener(id, data) {
if (this.refs.lmSubmitRef && `${id}` && data) {
/*
* 单纯的负责监听validateEvent事件,并记录接收到的信息,
*/
let map = [...this.state.validateMap];
// id 为input序号,以保证校验顺序
map[id.id] = data;
this.setState({
validateMap: map
});
}
}
onClick() {
// 这里setTimeout保证input 的 blur事件优先于button onClick事件执行
clearTimeout(this.timer);
this.timer = setTimeout(() => {
const { validateMap } = this.state;
let parmas = {};
let i = 0, len = validateMap.length;
for (i; i < len; i++) {
const item = validateMap[i];
if (!item.isValid) {
item.id = i;
// 判断是否需要submit控制input err状态
if (item.type === 'submitValidate') emitter.emit('inputErrEvent', item);
return this.props.onError(item);
} else if (item.name) {
parmas[item.name] = item.value;
}
}
this.props.onClick(parmas);
}, 22);
}
render() {
const { children, className, style, type, disabled, onClick, onError, ...arg } = this.props;
return (
<div ref={'lmSubmitRef'} className={`lm-submit ${className}`} style={{ cursor: 'pointer', ...style }}>
<Button
disabled={disabled}
handle={this.onClick}
{...arg}>
{children}
</Button>
</div>
)
}
}