Skip to content

Commit

Permalink
feat: form-binder add valueKey (alibaba#767)
Browse files Browse the repository at this point in the history
  • Loading branch information
wssgcg1213 authored Aug 2, 2018
1 parent 63b1108 commit 35949c3
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 4 deletions.
46 changes: 46 additions & 0 deletions react-materials/components/form-binder/demo/checkbox.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
---
title: 自定义 value key 的用法
order: 4
importStyle: true
---

有时候组件的取值属性不是 value,可以通过 valueKey 来进行修改

````jsx
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import FormBinderWrapper, {
FormBinder,
FormError
} from '@icedesign/form-binder';
import { Checkbox } from '@icedesign/base';

class App extends Component {

state = {
checkbox: true,
};

formChange = (state) => this.setState(state);

render() {
return (
<div>
<pre>{JSON.stringify(this.state, null, 2)}</pre>
<FormBinderWrapper
value={this.state}
onChange={this.formChange}
>
<div>
<FormBinder name="checkbox" valueKey="checked">
<Checkbox>Hello</Checkbox>
</FormBinder>
</div>
</FormBinderWrapper>
</div>
)
}
}

ReactDOM.render(<App />, mountNode);
````
12 changes: 8 additions & 4 deletions react-materials/components/form-binder/src/FormBinder.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,10 @@ export default class FormBinder extends Component {
* 触发校验的事件,对于高频触发校验的 Input 可以设置为 'onBlur' 减少校验调用次数
*/
triggerType: PropTypes.string,

/**
* value 属性的 key, 默认 `value`
*/
valueKey: PropTypes.string,
/**
* 当前表单项是否必须有值
*/
Expand Down Expand Up @@ -200,6 +203,7 @@ export default class FormBinder extends Component {
const FormItemProps = FormItem.props;

const currentName = this.props.name || FormItem.props.name;
const valueKey = this.props.valueKey || 'value';

// handle form field error
let formValueErrorProps = {};
Expand Down Expand Up @@ -246,10 +250,10 @@ export default class FormBinder extends Component {
this.context.validate(currentName, this.currentRules);
}
},
value: (() => {
[valueKey]: (() => {
// formItems value has higher priority
if (FormItemProps.value) {
return FormItemProps.value;
if (FormItemProps[valueKey]) {
return FormItemProps[valueKey];
} else {
return this.context.getter(currentName);
}
Expand Down

0 comments on commit 35949c3

Please sign in to comment.