zent
Version:
一套前端设计语言和基于React的实现
291 lines (235 loc) • 9.76 kB
JavaScript
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _class, _temp, _initialiseProps; /* eslint-disable no-underscore-dangle */
var _react = require('react');
var _isEqual = require('zent-utils/lodash/isEqual');
var _isEqual2 = _interopRequireDefault(_isEqual);
var _omit = require('zent-utils/lodash/omit');
var _omit2 = _interopRequireDefault(_omit);
var _utils = require('./utils');
var _unknownProps = require('./unknownProps');
var _unknownProps2 = _interopRequireDefault(_unknownProps);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Field = (_temp = _class = function (_Component) {
_inherits(Field, _Component);
// validationError为默认错误提示
// validationErrors为指定校验规则所对应的错误提示
function Field(props, context) {
_classCallCheck(this, Field);
var _this = _possibleConstructorReturn(this, (Field.__proto__ || Object.getPrototypeOf(Field)).call(this, props, context));
_initialiseProps.call(_this);
if (!context.zentForm) {
throw new Error('Field must be in zent-form');
}
_this.state = {
_value: props.value,
_isValid: true,
_isPristine: true,
_isValidating: false,
_pristineValue: props.value,
_validationError: [],
_externalError: null
};
_this._validations = props.validations || {};
return _this;
}
_createClass(Field, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps, nextState) {
return !(0, _isEqual2['default'])(nextState, this.state) || !(0, _isEqual2['default'])(nextProps, this.props);
}
}, {
key: 'componentWillMount',
value: function componentWillMount() {
if (!this.props.name) {
throw new Error('Form Field requires a name property when used');
}
this.context.zentForm.attachToForm(this);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if ('validations' in nextProps) {
this._validations = nextProps.validations;
}
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate(prevProps) {
// 支持props中的value动态更新
if (!(0, _isEqual2['default'])(this.props.value, prevProps.value)) {
this.setValue(this.props.value);
}
// 动态改变validation方法,重新校验
// if (!isEqual(this.props.validations, prevProps.validations)) {
// this.context.zentForm.validate(this)
// }
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.context.zentForm.detachFromForm(this);
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
var _props = this.props,
component = _props.component,
rest = _objectWithoutProperties(_props, ['component']);
var passableProps = this.processProps(_extends({}, rest, {
ref: function ref(_ref) {
_this2.wrappedComponent = _ref;
},
isTouched: !this.isPristine(),
isPristine: this.isPristine(),
isValid: this.isValid(),
value: this.format(this.getValue()),
error: this.getErrorMessage(),
errors: this.getErrorMessages(),
onChange: this.handleChange,
onBlur: this.handleBlur
}));
// 原生的标签不能传非标准属性进去
if (typeof component === 'string') {
return (0, _react.createElement)(component, _extends({}, (0, _omit2['default'])(passableProps, _unknownProps2['default'])));
}
return (0, _react.createElement)(component, passableProps);
}
}]);
return Field;
}(_react.Component), _class.propTypes = {
name: _react.PropTypes.string.isRequired,
component: _react.PropTypes.oneOfType([_react.PropTypes.func, _react.PropTypes.string]).isRequired,
normalize: _react.PropTypes.func
}, _class.defaultProps = {
validationError: '',
validationErrors: {}
}, _class.contextTypes = {
zentForm: _react.PropTypes.object
}, _initialiseProps = function _initialiseProps() {
var _this3 = this;
this.isPristine = function () {
return _this3.state._isPristine;
};
this.isValid = function () {
return _this3.state._isValid;
};
this.isValidating = function () {
return _this3.state._isValidating;
};
this.getPristineValue = function () {
return _this3.state._pristineValue;
};
this.getValue = function () {
return _this3.state._value;
};
this.setValue = function (value) {
_this3.setState({
_value: value,
_isPristine: false
}, function () {
_this3.context.zentForm.validate(_this3);
});
};
this.resetValue = function () {
_this3.setState({
_value: _this3.state._pristineValue,
_isPristine: true
}, function () {
_this3.context.zentForm.validate(_this3);
});
};
this.getWrappedComponent = function () {
return _this3.wrappedComponent;
};
this.getErrorMessage = function () {
var errors = _this3.getErrorMessages();
return errors.length ? errors[0] : null;
};
this.getErrorMessages = function () {
var _state = _this3.state,
_externalError = _state._externalError,
_validationError = _state._validationError;
return !_this3.isValid() ? _externalError || _validationError || [] : [];
};
this.normalize = function (value) {
var normalize = _this3.props.normalize;
if (!normalize) {
return value;
}
var previousValues = _this3.context.zentForm.getFormValues();
var previousValue = _this3.getValue();
var nextValues = _extends({}, previousValues, _defineProperty({}, _this3.props.name, value));
return normalize(value, previousValue, nextValues, previousValues);
};
this.format = function (value) {
var format = _this3.props.format;
if (!format) {
return value;
}
return format(value);
};
this.handleChange = function (event) {
var onChange = _this3.props.onChange;
var previousValue = _this3.getValue();
var newValue = _this3.normalize((0, _utils.getValue)(event));
var preventSetValue = false;
// 在传入的onChange中可以按需阻止更新value值
if (onChange) {
onChange(event, newValue, previousValue, function () {
return preventSetValue = true;
});
}
if (!preventSetValue) {
_this3.setValue(newValue);
}
};
this.handleBlur = function (event) {
var _props2 = _this3.props,
onBlur = _props2.onBlur,
asyncValidation = _props2.asyncValidation;
var previousValue = _this3.getValue();
var newValue = _this3.normalize((0, _utils.getValue)(event));
var preventSetValue = false;
if (onBlur) {
onBlur(event, newValue, previousValue, function () {
return preventSetValue = true;
});
}
if (!preventSetValue) {
_this3.setValue(newValue);
if (asyncValidation) {
_this3.context.zentForm.asyncValidate(_this3, newValue);
}
}
};
this.processProps = function (props) {
var type = props.type,
value = props.value,
rest = _objectWithoutProperties(props, ['type', 'value']);
if (type === 'checkbox') {
return _extends({}, rest, {
checked: !!value,
type: type
});
}
if (type === 'file') {
return _extends({}, rest, {
type: type
});
}
return props;
};
}, _temp);
exports['default'] = Field;
module.exports = exports['default'];