Skip to content

Commit

Permalink
v0.3.0 upgrade $defaultValue of <Field />
Browse files Browse the repository at this point in the history
  • Loading branch information
qiqiboy committed Aug 25, 2018
1 parent d624ef8 commit 37151a8
Show file tree
Hide file tree
Showing 9 changed files with 103 additions and 59 deletions.
23 changes: 22 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ Happy to build the forms in React ^\_^
+ [`defaultValue`](#defaultvalue-2)
+ [`validMessage`](#validmessage)
+ [`checked / unchecked`](#checked--unchecked)
+ [`valuePropName` `changePropName`](#valuepropname-changepropname)
- [`groupNode`](#groupnode)
- [`<Form />`](#form-)
+ [`render`](#render-1)
Expand Down Expand Up @@ -494,7 +495,13 @@ export default withField(FieldCustom, {
#### `type`
除了`select` `checkbox` `radio` `textarea` `group.checkbox` `group.radio`,其他都是渲染默认的 input,type 会原封不动传给 input。
设置控件类型,可以传入字符串或者自定义组件。
> v0.3.0 起,type 支持自定义组件
`type` 是字符串时,除了`select` `checkbox` `radio` `textarea` `group.checkbox` `group.radio`,其他都是渲染默认的 input,type 会原封不动传给 input。
`type` 是组件时,则会渲染该组件。
`type="select"` 时,还需要设置 option 子节点:
Expand Down Expand Up @@ -599,6 +606,20 @@ export default withField(FieldCustom, {
</label>
```
#### `valuePropName` `changePropName`
对于 type 设置为自定义组件时,如果组件的值以及值变动触发的更新回调方法不是默认的 value、onChange,可以通过这些参数更改:
```javascript
function MyComponent({ current, onUpdate }) {
return <button onClick={() => onUpdate(124)}>更新</button>;
}

<label>
<EasyField type={MyComponent} valuePropName="current" changePropName="onUpdate" /> 是否同意用户协议
</label>;
```
### `groupNode`
如果是 `group.checkbox` 或者 `group.radio` 类型,默认会渲染一个 div 节点。如果不希望渲染该 div 节点,可以通过`groupNode={null}`来禁用。
Expand Down
1 change: 0 additions & 1 deletion docs/app/modules/LoginForm/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,6 @@ class LoginForm extends Component {
type="textarea"
name="EasyField.textarea"
className="form-control"
defaultValue=""
minLength="10"
required
validMessage={{ required: '必需填写', minLength: '至少输入十个字符' }}
Expand Down
81 changes: 46 additions & 35 deletions lib/EasyField.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ var _createClass = function () { function defineProperties(target, props) { for

var _class, _temp, _class2, _temp2, _class3, _temp3;

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"); } }
Expand Down Expand Up @@ -63,15 +65,21 @@ var EasyField = (_temp = _class = function (_Component) {
typeStr = _props.type,
checked = _props.checked,
unchecked = _props.unchecked,
valuePropName = _props.valuePropName,
changePropName = _props.changePropName,
_onChange = _props.onChange,
_onFocus = _props.onFocus,
_onBlur = _props.onBlur,
otherProps = _objectWithoutProperties(_props, ['name', 'defaultValue', '$defaultValue', '$defaultState', '$validators', '$asyncValidators', '$onFieldChange', '$parser', '$formatter', 'validMessage', 'type', 'checked', 'unchecked', 'onChange', 'onFocus', 'onBlur']);
otherProps = _objectWithoutProperties(_props, ['name', 'defaultValue', '$defaultValue', '$defaultState', '$validators', '$asyncValidators', '$onFieldChange', '$parser', '$formatter', 'validMessage', 'type', 'checked', 'unchecked', 'valuePropName', 'changePropName', 'onChange', 'onFocus', 'onBlur']);

var fetchValueFromEvent = function fetchValueFromEvent(ev) {
return ev && ev.target ? ev.target[valuePropName] : ev;
};

var _typeStr$split = typeStr.split('.'),
_typeStr$split2 = _slicedToArray(_typeStr$split, 2),
type = _typeStr$split2[0],
groupType = _typeStr$split2[1];
var _ref = isFunction(typeStr) ? [typeStr] : typeStr.split('.'),
_ref2 = _slicedToArray(_ref, 2),
type = _ref2[0],
groupType = _ref2[1];

var fieldProps = {
name: name,
Expand Down Expand Up @@ -103,7 +111,7 @@ var EasyField = (_temp = _class = function (_Component) {
fieldProps.$defaultValue = $defaultValue;
}

var Element = 'input';
var Element = isFunction(type) ? type : 'input';
var _defaultValue = void 0;

switch (type) {
Expand Down Expand Up @@ -138,6 +146,8 @@ var EasyField = (_temp = _class = function (_Component) {
Field,
fieldProps,
function (props) {
var _elemProps;

if (type === 'group') {
_this3.$fieldProps = {
$fieldutil: props,
Expand Down Expand Up @@ -216,28 +226,23 @@ var EasyField = (_temp = _class = function (_Component) {
break;

default:
elemProps = {
value: 'compositionValue' in _this3 ? _this3.compositionValue : $formatter(props.$value),
onCompositionEnd: function onCompositionEnd(ev) {
_this3.composition = false;
delete _this3.compositionValue;
elemProps.onChange(ev);
},
onCompositionStart: function onCompositionStart() {
return _this3.composition = true;
},
onChange: function onChange(ev) {
var value = ev.target.value;

if (_this3.composition) {
_this3.compositionValue = value;
_this3.forceUpdate();
} else {
props.$render($parser(value));
_onChange && _onChange(ev);
}
elemProps = (_elemProps = {}, _defineProperty(_elemProps, valuePropName, 'compositionValue' in _this3 ? _this3.compositionValue : $formatter(props.$value)), _defineProperty(_elemProps, 'onCompositionEnd', function onCompositionEnd(ev) {
_this3.composition = false;
delete _this3.compositionValue;
elemProps[changePropName](ev);
}), _defineProperty(_elemProps, 'onCompositionStart', function onCompositionStart() {
return _this3.composition = true;
}), _defineProperty(_elemProps, changePropName, function (ev) {
var value = fetchValueFromEvent(ev);

if (_this3.composition) {
_this3.compositionValue = value;
_this3.forceUpdate();
} else {
props.$render($parser(value));
_onChange && _onChange(ev);
}
};
}), _elemProps);
break;
}

Expand Down Expand Up @@ -267,13 +272,15 @@ var EasyField = (_temp = _class = function (_Component) {

return EasyField;
}(Component), _class.displayName = 'React.formutil.EasyField', _class.propTypes = {
type: PropTypes.string.isRequired,
type: PropTypes.oneOfType([PropTypes.string, PropTypes.func]).isRequired,
defaultValue: PropTypes.any,
checked: PropTypes.any,
unchecked: PropTypes.any,
validMessage: PropTypes.object,
render: PropTypes.func,
groupNode: PropTypes.any,
valuePropName: PropTypes.string,
changePropName: PropTypes.string,

$parser: PropTypes.func,
$formatter: PropTypes.func
Expand All @@ -283,15 +290,18 @@ var EasyField = (_temp = _class = function (_Component) {
unchecked: false,
validMessage: {},

valuePropName: 'value',
changePropName: 'onChange',

$parser: function $parser(value) {
return value;
},
$formatter: function $formatter(value) {
return value;
}
}, _class.defaultValidators = [['required', function ($value, check, _ref) {
var type = _ref.type,
checked = _ref.checked;
}, _class.defaultValidators = [['required', function ($value, check, _ref3) {
var type = _ref3.type,
checked = _ref3.checked;
return type === 'checkbox' || type === 'radio' ? $value === checked : !isEmpty($value);
}], ['maxLength', function ($value, len) {
return isEmpty($value) || $value.length <= len;
Expand All @@ -312,9 +322,9 @@ var EasyField = (_temp = _class = function (_Component) {
validKey = _item[0],
validate = _item[1];

$validators[validKey] = function validator($value, propValue, _ref2) {
var _ref2$validMessage = _ref2.validMessage,
validMessage = _ref2$validMessage === undefined ? {} : _ref2$validMessage;
$validators[validKey] = function validator($value, propValue, _ref4) {
var _ref4$validMessage = _ref4.validMessage,
validMessage = _ref4$validMessage === undefined ? {} : _ref4$validMessage;

return validate.apply(undefined, arguments) || validMessage[validKey] || 'Error input: ' + validKey;
};
Expand Down Expand Up @@ -387,7 +397,8 @@ var EasyFieldGroupOption = (_temp3 = _class3 = function (_Component3) {
} : $groupType === 'checkbox' ? {
checked: $formatter($fieldutil.$value).indexOf($value) > -1,
onChange: function onChange(ev) {
$fieldutil.$render($parser(ev.target.checked ? $fieldutil.$value.concat($value) : $fieldutil.$value.filter(function (value) {
var valueArr = $fieldutil.$value || [];
$fieldutil.$render($parser(ev.target.checked ? valueArr.concat($value) : valueArr.filter(function (value) {
return value !== $value;
})));

Expand Down
4 changes: 1 addition & 3 deletions lib/Field.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ var Field = (_temp = _class = function (_Component) {
_initialiseProps.call(_this);

_this.$baseState = Object.assign({
$value: props.$defaultValue,
$value: '$defaultValue' in props ? props.$defaultValue : '',

$valid: true,
$invalid: false,
Expand Down Expand Up @@ -178,8 +178,6 @@ var Field = (_temp = _class = function (_Component) {

$validators: PropTypes.object,
$asyncValidators: PropTypes.object
}, _class.defaultProps = {
$defaultValue: ''
}, _class.contextTypes = {
$$register: PropTypes.func,
$$unregister: PropTypes.func,
Expand Down
4 changes: 2 additions & 2 deletions lib/Form.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ var Form = (_temp2 = _class = function (_Component) {
$params: utils.toObject($stateArray, function ($params, _ref8) {
var path = _ref8.path,
$state = _ref8.$state;
return utils.parsePath($params, path, $state.$value);
return (!utils.isUndefined($state.$value) || $state.$dirty) && utils.parsePath($params, path, $state.$value);
}, Object.assign({}, this.$$defaultValues)),
$errors: utils.toObject($stateArray, function ($errors, _ref9) {
var path = _ref9.path,
Expand Down Expand Up @@ -148,7 +148,7 @@ var Form = (_temp2 = _class = function (_Component) {
$weakParams: utils.toObject($stateArray, function ($params, _ref14) {
var path = _ref14.path,
$state = _ref14.$state;
return $params[path] = $state.$value;
return (!utils.isUndefined($state.$value) || $state.$dirty) && ($params[path] = $state.$value);
}),
$weakErrors: utils.toObject($stateArray, function ($errors, _ref15) {
var path = _ref15.path,
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "react-formutil",
"version": "0.2.24",
"version": "0.3.0",
"description": "Happy to build the forms in React ^_^",
"main": "lib/index.js",
"directories": {
Expand Down
31 changes: 22 additions & 9 deletions src/EasyField.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@ class EasyField extends Component {
static displayName = 'React.formutil.EasyField';

static propTypes = {
type: PropTypes.string.isRequired,
type: PropTypes.oneOfType([PropTypes.string, PropTypes.func]).isRequired,
defaultValue: PropTypes.any,
checked: PropTypes.any,
unchecked: PropTypes.any,
validMessage: PropTypes.object,
render: PropTypes.func,
groupNode: PropTypes.any,
valuePropName: PropTypes.string,
changePropName: PropTypes.string,

$parser: PropTypes.func,
$formatter: PropTypes.func
Expand All @@ -32,6 +34,9 @@ class EasyField extends Component {
unchecked: false,
validMessage: {},

valuePropName: 'value',
changePropName: 'onChange',

$parser: value => value,
$formatter: value => value
};
Expand Down Expand Up @@ -82,13 +87,19 @@ class EasyField extends Component {
type: typeStr,
checked,
unchecked,
valuePropName,
changePropName,
onChange,
onFocus,
onBlur,
...otherProps
} = this.props;

const [type, groupType] = typeStr.split('.');
const fetchValueFromEvent = function(ev) {
return ev && ev.target ? ev.target[valuePropName] : ev;
};

const [type, groupType] = isFunction(typeStr) ? [typeStr] : typeStr.split('.');

const fieldProps = {
name,
Expand Down Expand Up @@ -123,7 +134,7 @@ class EasyField extends Component {
fieldProps.$defaultValue = $defaultValue;
}

let Element = 'input';
let Element = isFunction(type) ? type : 'input';
let _defaultValue;

switch (type) {
Expand Down Expand Up @@ -232,15 +243,16 @@ class EasyField extends Component {

default:
elemProps = {
value: 'compositionValue' in this ? this.compositionValue : $formatter(props.$value),
[valuePropName]:
'compositionValue' in this ? this.compositionValue : $formatter(props.$value),
onCompositionEnd: ev => {
this.composition = false;
delete this.compositionValue;
elemProps.onChange(ev);
elemProps[changePropName](ev);
},
onCompositionStart: () => (this.composition = true),
onChange: ev => {
const value = ev.target.value;
[changePropName]: ev => {
const value = fetchValueFromEvent(ev);

if (this.composition) {
this.compositionValue = value;
Expand Down Expand Up @@ -337,11 +349,12 @@ class EasyFieldGroupOption extends Component {
? {
checked: $formatter($fieldutil.$value).indexOf($value) > -1,
onChange: ev => {
const valueArr = $fieldutil.$value || [];
$fieldutil.$render(
$parser(
ev.target.checked
? $fieldutil.$value.concat($value)
: $fieldutil.$value.filter(value => value !== $value)
? valueArr.concat($value)
: valueArr.filter(value => value !== $value)
)
);

Expand Down
6 changes: 1 addition & 5 deletions src/Field.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,6 @@ class Field extends Component {
$asyncValidators: PropTypes.object
};

static defaultProps = {
$defaultValue: ''
};

static contextTypes = {
$$register: PropTypes.func,
$$unregister: PropTypes.func,
Expand All @@ -43,7 +39,7 @@ class Field extends Component {
super(props, context);

this.$baseState = {
$value: props.$defaultValue,
$value: '$defaultValue' in props ? props.$defaultValue : '',

$valid: true,
$invalid: false,
Expand Down
10 changes: 8 additions & 2 deletions src/Form.js
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,9 @@ class Form extends Component {
$states: utils.toObject($stateArray, ($states, { path, $state }) => utils.parsePath($states, path, $state)),
$params: utils.toObject(
$stateArray,
($params, { path, $state }) => utils.parsePath($params, path, $state.$value),
($params, { path, $state }) =>
(!utils.isUndefined($state.$value) || $state.$dirty) &&
utils.parsePath($params, path, $state.$value),
{
...this.$$defaultValues
}
Expand All @@ -293,7 +295,11 @@ class Form extends Component {
),

$weakStates: utils.toObject($stateArray, ($states, { path, $state }) => ($states[path] = $state)),
$weakParams: utils.toObject($stateArray, ($params, { path, $state }) => ($params[path] = $state.$value)),
$weakParams: utils.toObject(
$stateArray,
($params, { path, $state }) =>
(!utils.isUndefined($state.$value) || $state.$dirty) && ($params[path] = $state.$value)
),
$weakErrors: utils.toObject($stateArray, ($errors, { path, $state }) => {
if ($state.$invalid) {
$errors[path] = $state.$error;
Expand Down

0 comments on commit 37151a8

Please sign in to comment.