Giter VIP home page Giter VIP logo

form's Introduction

rc-form

React High Order Form Component.

NPM version build status Test coverage gemnasium deps node version npm download Code Quality: Javascript Total alerts

Development

npm install
npm start
open http://localhost:8000/examples/

Feature

  • Support react.js and even react-native
  • Validate fields with async-validator

Install

rc-form

Usage

import { createForm, formShape } from 'rc-form';

class Form extends React.Component {
  static propTypes = {
    form: formShape,
  };

  submit = () => {
    this.props.form.validateFields((error, value) => {
      console.log(error, value);
    });
  }

  render() {
    let errors;
    const { getFieldProps, getFieldError } = this.props.form;
    return (
      <div>
        <input {...getFieldProps('normal')}/>
        <input {...getFieldProps('required', {
          onChange(){}, // have to write original onChange here if you need
          rules: [{required: true}],
        })}/>
        {(errors = getFieldError('required')) ? errors.join(',') : null}
        <button onClick={this.submit}>submit</button>
      </div>
    );
  }
}

export createForm()(Form);

Use with React Native

Expo preview

avatar

View the source code

Or a quicker version:

import { createForm } from 'rc-form';

class Form extends React.Component {
  componentWillMount() {
    this.requiredDecorator = this.props.form.getFieldDecorator('required', {
      rules: [{required: true}],
    });
  }

  submit = () => {
    this.props.form.validateFields((error, value) => {
      console.log(error, value);
    });
  }

  render() {
    let errors;
    const { getFieldError } = this.props.form;
    return (
      <div>
        {this.requiredDecorator(
          <input
            onChange={
              // can still write your own onChange
            }
          />
        )}
        {(errors = getFieldError('required')) ? errors.join(',') : null}
        <button onClick={this.submit}>submit</button>
      </div>
    );
  }
}

export createForm()(Form);

createForm(option: Object) => (WrappedComponent: React.Component) => React.Component

Option Description Type Default
option.validateMessages Preseted messages of async-validator Object {}
option.onFieldsChange Called when field changed, you can dispatch fields to redux store. (props, changed, all): void NOOP
option.onValuesChange Called when value changed. (props, changed, all): void NOOP
option.mapProps Get new props transferred to WrappedComponent. (props): Object props => props
option.mapPropsToFields Convert value from props to fields. Used for read fields from redux store. (props): Object NOOP
option.fieldNameProp Where to store the name argument of getFieldProps. String -
option.fieldMetaProp Where to store the meta data of getFieldProps. String -
option.fieldDataProp Where to store the field data String -
option.withRef(deprecated) Maintain an ref for wrapped component instance, use refs.wrappedComponent to access. boolean false

Note: use wrappedComponentRef instead of withRef after [email protected]

class Form extends React.Component { ... }

// deprecated
const EnhancedForm = createForm({ withRef: true })(Form);
<EnhancedForm ref="form" />
this.refs.form.refs.wrappedComponent // => The instance of Form

// Recommended
const EnhancedForm = createForm()(Form);
<EnhancedForm wrappedComponentRef={(inst) => this.formRef = inst} />
this.formRef // => The instance of Form

(WrappedComponent: React.Component) => React.Component

The returned function of createForm(). It will pass an object as prop form with the following members to WrappedComponent:

getFieldProps(name, option): Object { [valuePropName], [trigger], [validateTrigger] }

Will create props which can be set on a input/InputComponent which support value and onChange interface.

After set, this will create a binding with this input.

<form>
  <input {...getFieldProps('name', { ...options })} />
</form>

name: String

This input's unique name.

option: Object

Option Description Type Default
option.valuePropName Prop name of component's value field, eg: checkbox should be set to checked ... String 'value'
option.getValueProps Get the component props according to field value. (value): Object (value) => ({ value })
option.getValueFromEvent Specify how to get value from event. (e): any See below
option.initialValue Initial value of current component. any -
option.normalize Return normalized value. (value, prev, all): Object -
option.trigger Event which is listened to collect form data. String 'onChange'
option.validateTrigger Event which is listened to validate. Set to falsy to only validate when call props.validateFields. String String[]
option.rules Validator rules. see: async-validator Object[] -
option.validateFirst Whether stop validate on first rule of error for this field. boolean false
option.validate Object[] -
option.validate[n].trigger Event which is listened to validate. Set to falsy to only validate when call props.validateFields. String String[]
option.validate[n].rules Validator rules. see: async-validator Object[] -
option.hidden Ignore current field while validating or gettting fields boolean false
option.preserve Whether to preserve the value. That will remain the value when the field be unmounted and be mounted again boolean false
Default value of getValueFromEvent
function defaultGetValueFromEvent(e) {
  if (!e || !e.target) {
    return e;
  }
  const { target } = e;
  return target.type === 'checkbox' ? target.checked : target.value;
}
Tips
{
  validateTrigger: 'onBlur',
  rules: [{required: true}],
}
// is the shorthand of
{
  validate: [{
    trigger: 'onBlur',
    rules: [{required: true}],
  }],
}

getFieldDecorator(name:String, option: Object) => (React.Node) => React.Node

Similar to getFieldProps, but add some helper warnings and you can write onXX directly inside React.Node props:

<form>
  {getFieldDecorator('name', otherOptions)(<input />)}
</form>

getFieldsValue([fieldNames: String[]])

Get fields value by fieldNames.

getFieldValue(fieldName: String)

Get field value by fieldName.

getFieldInstance(fieldName: String)

Get field react public instance by fieldName.

setFieldsValue(obj: Object)

Set fields value by kv object.

setFieldsInitialValue(obj: Object)

Set fields initialValue by kv object. use for reset and initial display/value.

setFields(obj: Object)

Set fields by kv object. each field can contain errors and value member.

validateFields([fieldNames: String[]], [options: Object], callback: (errors, values) => void)

Validate and get fields value by fieldNames.

options is the same as validate method of async-validator. And add force.

options.force: Boolean

Defaults to false. Whether to validate fields which have been validated(caused by validateTrigger).

getFieldsError(names): Object{ [name]: String[] }

Get inputs' validate errors.

getFieldError(name): String[]

Get input's validate errors.

isFieldValidating(name: String): Bool

Whether this input is validating.

isFieldsValidating(names: String[]): Bool

Whether one of the inputs is validating.

isFieldTouched(name: String): Bool

Whether this input's value had been changed by user.

isFieldsTouched(names: String[]): Bool

Whether one of the inputs' values had been changed by user.

resetFields([names: String[]])

Reset specified inputs. Defaults to all.

isSubmitting(): Bool (Deprecated)

Whether the form is submitting.

submit(callback: Function) (Deprecated)

Cause isSubmitting to return true, after callback called, isSubmitting return false.

rc-form/lib/createDOMForm(option): Function

createDOMForm enhancement, support props.form.validateFieldsAndScroll

validateFieldsAndScroll([fieldNames: String[]], [options: Object], callback: (errors, values) => void)

props.form.validateFields enhancement, support scroll to the first invalid form field, scroll is the same as dom-scroll-into-view's function parameter config.

options.container: HTMLElement

Defaults to first scrollable container of form field(until document).

Notes

  • Do not use stateless function component inside Form component: facebook/react#6534

  • you can not set same prop name as the value of validateTrigger/trigger for getFieldProps

<input {...getFieldProps('change',{
  onChange: this.iWantToKnow // you must set onChange here or use getFieldDecorator to write inside <input>
})}>
  • you can not use ref prop for getFieldProps
<input {...getFieldProps('ref')} />

this.props.form.getFieldInstance('ref') // use this to get ref

or

<input {...getFieldProps('ref',{
  ref: this.saveRef // use function here or use getFieldDecorator to write inside <input> (only allow function)
})} />

Test Case

npm test
npm run chrome-test

Coverage

npm run coverage

open coverage/ dir

License

rc-form is released under the MIT license.

form's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

form's Issues

createClass will be deprecated in React 16

When upgrading React:

Warning: Form: React.createClass is deprecated and will be removed in version 16. Use plain JavaScript classes instead. If you're not yet ready to migrate, create-react-class is available on npm as a drop-in replacement.

I have some some trouble with 'getFieldProps'.

this code work well:

var field = this.getField(name);
        var fieldValue = fieldMeta.initialValue;
        if (field && 'value' in field) {
          fieldValue = field.value;
        }

but the new version in my code is work strange:

const field = exclusive ? this.getField(leadingName) : this.getField(name);
        let fieldValue = atom;
        if (field && 'value' in field) {
          fieldValue = field.value;
        }
        if (fieldValue === atom) {
          fieldValue = exclusive ? fieldsMeta[leadingName].initialValue : fieldMeta.initialValue;
        }

I want to konw 'atom' what use?

【建议】提供动态设置validte相关api

在用form表单时,经常需要封装一些自定义组件,相对应的检验规则希望能在这些组件中动态设置,而不是统一在使用getFieldDecorator时传入。

Checkbox.AgreeItem on onChange?

Checkbox.AgreeItem on onChange?

 <div>
          <Checkbox.AgreeItem checked={this.state.isAgree}
                              onChange={()=>{alert('同间协议')}}>我已阅读并同意<a
            onClick={(e) => { e.preventDefault(); alert('打开协议'); }}>会员注册协议</a></Checkbox.AgreeItem>
        </div>

Support nested objects and array

In input form

{getFieldDecorator('member[0].name.firstname', {})(<input/>)}
{getFieldDecorator('member[1].name.firstname', {})(<input/>)}

this.props.form.getFieldsValue() 返回数据结构为

members: [{ name: {firstname: "xxx"} }, { name: {firstname: "yyy"} }]

onFieldsChange 的 fields 参数各字段中 ‘instance’ 属性存在循环结构,导致 Redux DevTools 报错

目前将 fields 直接存储到 redux store 中,但是会遇到如下的错误:

VM3378:21 Uncaught TypeError: Converting circular structure to JSON

经排查后发现这是 Redux DevTools 报的错,由 fields 各字段中的 'instance' 引起,在 dispatch 前删掉就可以正常。

现在想问下,这个属性的作用是什么,可以删掉吗?如果删掉没问题最好还是在 onFieldsChange 的参数中就干掉。

Validation state change.

Need some functionality (e.g. callback) which trigger only on validate state change (valid/invalid).
Or is it already possible to do?
Thanks

Using normalize but still get unformatted data in the onSubmit callback

The problem is that the value of the input field is 1000 it then gets normalized into 1,000 which is all good but on onSubmit the value is 1.000 but I want it to be unformatted.

I tried using normalize and getValueFromEvent together with no success. Maybe this is not possible and has to be done outside the scope of rc-form.

I can't access rc-select and slider components values

I am trying to create a form using rc-select and rc-slider components, check my render

render() {
        const { getFieldProps, getFieldError } = this.props.form;
        const errorEMail = getFieldError('email');
        return(
            <div style={ regionStyle }>
                <div style={style}>
                    <Slider range allowCross={false} defaultValue={[0, 20]} handle={<CustomHandle />} onChange={log} />
                </div>
                <div>
                    <div style={{ width: 300 }}>
                        <label htmlFor="country">Country</label>
                        <Select
                            placeholder="select your country"
                            defaultActiveFirstOption={false}
                            showSearch={false}
                            style={{ width: 500 }}
                            onChange={onChange}
                            combobox
                        >
                            <OptGroup label="manager">
                                <Option value="jack">
                                    <b style={{color: 'red'}}>
                                        jack
                                    </b>
                                </Option>
                                <Option value="lucy">lucy</Option>
                            </OptGroup>
                            <OptGroup label="engineer">
                                <Option value="yiminghe">yiminghe</Option>
                            </OptGroup>
                        </Select>
                    </div>
                </div>
                <div>
                    <label htmlFor="email">E-mail</label>
                    <input {...getFieldProps('email', {
                        validateFirst: true,
                        rules: [
                            {
                                required: true,
                            },
                            {
                                type: 'email',
                                message: 'Invalid E-mail',
                            }
                        ],
                        validateTrigger: 'onBlur',
                        id: 'email'
                    })}
                    />
                    <div style={errorStyle}>
                        {(errorEMail) ? errorEMail.join(',') : null}
                    </div>
            </div>

            <button onClick={this.submit}>Search</button>
        </div>);
    },

When I submit the button I only get access to input , bue select and slides values are not availble, this is my submit function

submit(e) {
        e.preventDefault();
        this.props.form.validateFields((error, values) => {
            if (!error) {
                console.log('ok', values);
            } else {
                console.log('error', error, values);
            }
     });
    },

Check the output

screen shot 2016-08-13 at 1 05 25 pm

How could I access those values?

动态 form 中 name 不变时, getFieldProps 先于 saveRef 触发, 导致 fieldMeta 为 undefined, 引发报错

错误:

image

Form 由于使用了高阶组件, 先调用了 getFieldProps , 包含初始化 fieldMeta

fieldMeta = fieldsMeta[name] = fieldsMeta[name] || {};

rc-form 重载了 ref

inputProps.ref = this.getCacheBind(name, `${name}__ref`, this.saveRef);

该方法会在 component unmount 时调用

image

saveRef 清理了 meta state

      saveRef(name, _, component) {
        if (!component) {
          // after destroy, delete data
          delete this.fieldsMeta[name];
          delete this.fields[name];
          delete this.instances[name];
          delete this.cachedBind[name];
          return;
        }
        const fieldMeta = this.getFieldMeta(name); // 第二次调用时 由于 fieldMeta 为空, 所以并不会执行 ref(component)
        if (fieldMeta) {
          const ref = fieldMeta.ref;
          if (ref) {
            if (typeof ref === 'string') {
              throw new Error(`can not set ref string for ${name}`);
            }
            ref(component);
          }
        }
        this.instances[name] = component;
      },

在 react attachRef时, saveRef 会再次被调用, 但此时 fieldMeta 已经在 unmount 时被删除了
image

所以此时 ref(component) 不会被触发, 导致报错

image

form.validateFields(err, value) 中拿到的值应该使用 transform 预处理

在使用 rc-form 时,我定义了一个剔除头尾空白的逻辑(用户输入过程中可以在尾部输入空白,然后继续输入其他有效内容,即空白可以出现中中间),同时这个逻辑可以避免用户输入全部是空白的无效内容。

rules: [
  {required: true, transform: value => String(value).trim() },
],

但是在 form.validateFields(err, value) 中拿到的值确实未经处理的,这个时候需要再做一次同样的处理逻辑(实际校验通过的内容,和提交时拿到的却是通不过校验的原始内容,不一致)。

建议 validateFields 时的结果值应该经过 transform 预处理。

what is magic about getFieldDecorator and initialValue?

I have 2 custom components:

(1) is working - I don't have to provide initialValue
component with valuePropName as string

{getFieldDecorator('background', { valuePropName: 'color'})(
	<ColorPicker/>
)}

(2) is NOT working - I HAVE to provide initialValue
component with valuePropName as array

{getFieldDecorator('range', { valuePropName: 'limit', initialValue: get(info, 'range')})(
	<RangeInput/>
)}

能不能更新一下 file input 的例子为使用getFieldDecorator的?

我按照以下两个例子,试图把file input的 formData 放在redux中,但是出现了报错.
实在不知道使用getFieldDecorator正确的写法是怎么样的?
能否更新一下getFieldDecorator的那个例子?
谢谢

http://react-component.github.io/form/examples/redux.html
http://react-component.github.io/form/examples/file-input.html

getValueFromFileEvent({ target }) {
      return  {target};
}
...

{getFieldDecorator('contentFile', {
    getValueFromEvent: this.getValueFromFileEvent.bind(this),
})(<input   type="file" />)}

...

export default connect(mapStoreToProps, mapDispatchToProps)(Form.create({
    mapPropsToFields(props) {
        return {
            contentFile: props.formData.contentFile,
        };
    },
    onFieldsChange(props, fields) {
        props.setTemplateForm(fields);
    },
})(AddTemplate));

报错:

Warning: AddTemplate is changing an uncontrolled input of type file to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://fb.me/react-controlled-components

Uncaught DOMException: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.

mapPropsToFields 能否增加一个 nowProps

目前 mapPropsToFields 不能有效的替代 componentWillReceiveProps
因为在 componentWillReceiveProps 里可以通过 this.props 获得当前的props。
而mapPropsToFields 没法获取到 当前的 props

API

@connect({
  // redux
}) 
@form({
  mapPropsToFields(props) {
    // props.user: {value,error,validating}
    return {
      user: props.user
    };
  },
  onFieldChange(props,field) {
    // field: {name, value, error,validating}
     props.dispatch(...)
  }
})
class App extends Component {
  oSubmit(e) {
    this.props.form.validate((error) => {
       if(!error){
         var values = this.props.form.getFieldsValue();
         // ...
       }
    });
  },

  render() {
    const {
      getField, getFieldError, getFieldValue, 
      setFieldsValue,
      isFieldValidating,
      getFieldsValue,reset, removeField
    } = this.props.form;
    let error;
    return <div>
      <form onSubmit={this.oSubmit}>
      <input {...getField({
      name: 'user',
      rules: [[{required: true, min: 5}, {validator: this.userExists}]],
      trigger:'onBlur' // defaults to onChange
     })}/>
     {error = getFieldError('user') ? error : null}
     {isFieldValidating('user') ? 'validating': null}  
   </div>;
  }
}

how to map array of object to field

数据结构类似于:

{
  title: 'test',
  items: [{
    id: 1
    title: 'xxx'
  }, {
    id: 2
    title: 'xxxx'
  }]
}

根据 input-array 这个例子,
先使用

getFieldValue('items').map

但是 map 里的 input 怎么关联到 id 和 title 这样的字段呢

{...getFieldProps('item.title')}

并没有生效

How to clear fields after submitting form?

For the life of me I can't seem to figure out how to clear the input boxes after submission.

resetFields doesn't work. setInitialiValues doesn't work. Very frustrating!

warning

Form is changing an uncontrolled input of type undefined to be controlled. Input elements should not switch from uncontrolled to controlled(or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://fb.me/react-controlled-components

this.props.form.resetFields() not work?

reset() {
    this.props.form.resetFields()
}

render() {
   const { getFieldProps } = this.props.form
   const formItemLayout = {
     labelCol: { span: 4 },
     wrapperCol: { span: 20 },
}

return (
    <div>
        <a onClick={::this.showModal}>修改</a>
        <Modal title="编辑权限"
            maskClosable={false}
            visible={this.state.modalVisible}
            onOk={this.handleSubmit}
            onCancel={this.hideModal}
        >
            <Form horizontal form={this.props.form}>
                <FormItem
                    {...formItemLayout}
                    label="菜单权限名称"
                >
                    <Input {...getFieldProps('menu_title', {})} />
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="url"
                >
                    <Input {...getFieldProps('url', {})} />
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="排序编号"
                >
                    <InputNumber {...getFieldProps('sort_num', {})} min={1} defaultValue={0} />
                </FormItem>
                <Button type="ghost" onClick={::this.reset}>重置</Button>
            </Form>
        </Modal>
    </div>
)
}

Who can give me some advice? thx!

validateFields 会触发 form 的 onFieldsChange 回调

使用如下的方式给 form 绑定上 onChange 回调后,调用 validateFields 或者validateFieldsAndScroll 时会触发该回调,这样会导致需要验证的域在改变的时候会触发两次该回调。

Form.create({
  onFieldsChange(props, changedFields) {
    props.onChange(changedFields);
  }
})(BaseForm);

强制插入了 value props

image

代码里这个逻辑必然会进来,是正确的?验证状态就不能只设置 defaultValue 了吗?除了input外 select 、tree-select 都有 defaultValue,不受控也应该可以被验证的

feature: getFieldValue(field: String)

当我想判断一个 field 的 value 是否为空串时,现在只能这样:

if (!!getFieldsValue(['name']).name) {
  // do something
}

想增加一个 getFieldValue 函数,就可以用下面的方式访问:

if (!!getFieldsValue('name')) {
  // do something
}

如果增加 getFieldValue,是否也需增加一个对应的 setFieldValue(fieldName, value)?

@yiminghe

form validation incorrect when use deep validation

when use deep rule validation, as following, if onChange get partial value : {name:"hello"}, the validation of form will not be error.

I think the error may be in the code,

https://github.com/react-component/form/blob/master/src/createBaseForm.js#L503

which test the Field.error and Field.subField.error,

nowField.errors = fieldErrors && fieldErrors.errors;

here need to be OR relationship?

the case code :

    const proxyRule = {                                                                                                                                                                      
      type: 'object', required: true, message: 'proxy 信息',                                                                                                                                 
      fields: {                                                                                                                                                                              
        name: { type: 'string', required: true, message: 'proxy主机名' },                                                                                                                    
        ipv4: { type: 'string', required: true, message: 'proxy Ip' },                                                                                                                       
      }                                                                                                                                                                                      
    };  

and formItem use it :

<FormItem                                                                                                                                                                            
          {...formItemLayoutWithOutLabel}                                                                                                                                                    
          inline                                                                                                                                                                             
          hasFeedback                                                                                                                                                                        
          key={id}                                                                                                                                                                           
        >                                                                                                                                                                                    
          {                                                                                                                                                                                  
            getFieldDecorator(`proxy-${id}`, {                                                                                                                                               
              rules: [proxyRule],                                                                                                                                                            
              initialValue: { name, ipv4 }                                                                                                                                                   
            })(<ProxyAdd removable={proxyCount !== 1} remove={this.remove(id)} />)                                                                                                           
          }                                                                                                                                                                                  
        </FormItem> 

component ProxyAdd:

class ProxyAdd extends Component {                                                                                                                                                           
  constructor(props) {                                                                                                                                                                       
    super(props);                                                                                                                                                                            
    const { name, ipv4 } = this.props.value || {};                                                                                                                                           
    this.state = {                                                                                                                                                                           
      name, ipv4                                                                                                                                                                             
    };                                                                                                                                                                                       
  }                                                                                                                                                                                          
                                                                                                                                                                                             
  updateState = (key) => (e) => {                                                                                                                                                            
    const state = {};                                                                                                                                                                        
    state[key] = e.target.value;                                                                                                                                                             
    this.setState(state);                                                                                                                                                                    
    this.props.onChange({ ...this.state, ...state });                                                                                                                                        
  }                                                                                                                                                                                          
                                                                                                                                                                                             
  render() {                                                                                                                                                                                 
    const { removable } = this.props;                                                                                                                                                        
    const { name, ipv4 } = this.state;                                                                                                                                                       
                                                                                                                                                                                             
    return (                                                                                                                                                                                 
      <Input.Group>                                                                                                                                                                          
        <Col span="8">                                                                                                                                                                       
          <Input                                                                                                                                                                             
            type="text"                                                                                                                                                                      
            value={name}                                                                                                                                                                     
            placeholder="proxy name"                                                                                                                                                         
            onChange={this.updateState('name')} />                                                                                                                                           
        </Col>                                                                                                                                                                               
        <Col span="6">                                                                                                                                                                       
          <Input                                                                                                                                                                             
            type="text"                                                                                                                                                                      
            placeholder="ipv4"                                                                                                                                                               
            value={ipv4}                                                                                                                                                                     
            onChange={this.updateState('ipv4')} />                                                                                                                                           
        </Col>         
      </Input.Group>                                                                                                                                                                                                                                                                                                                                          
    );                                                                                                                                                                                       
  }                                                                                                                                                                                          
 }         

https://github.com/react-component/form/blob/master/src/createBaseForm.js#L503

渲染性能问题

每次输入都会触发整个表单render,当表单项多时,整个表单很卡,有办法可以避免嘛?

feat: `getFieldProps` 返回值增加 `name`

rc-form 应该不会集成到 antd 里面了,毕竟是纯功能的,而且集成进去可能会导致 antd.Form 变复杂。

但是觉得可以利用 rc-form 简化 FormItem 的用法,如果 getFieldProps 的返回值增加 name 字段,那么 FormItemvalidateStatushelp 都可以自行计算出来,就不需要用户传入了。当然,如果用户传入,就会优先使用用户设置的值。

        <FormItem
          label="用户名:"
          id="name"
          labelCol={{span: 7}}
          wrapperCol={{span: 12}}
          validateStatus={this.getValidateStatus('name')}  // 可自动生成
          hasFeedback
          help={(getFieldError('name') || []).join(', ')}  // 可自动生成
          required>
          <Input {...getFieldProps('name', {
            rules: [
              {require: true, min: 5, message: '用户名至少为 5 个字符'},
              {validator: this.userExists},
            ],
          })} id="name" placeholder="实时校验,输入 JasonWood 看看" />
        </FormItem>

当然,如果连 required 都暴露出来的话,FormItem[required] 也可以自动设置,不过这个需要计算,而 name 值则是直接使用 getFieldProps 的第一个参数就行。

@yiminghe

extending async-validator rules

I'd like to add custom rules to the async-validator library used. There is a register method on the AsyncValidator constructor.

It would be nice if rc-form would expose that in some way. Either export the AsyncValidator in a separate file and have baseForm import that file. You could then import AsyncValidator in your own project and register rules before calling createForm?

// base
import AsyncValidator from './AsyncValidator'
// my-lib
import AsyncValidator from 'rc-form/AsyncValidator'
AsyncValidator.register('customRule', () => {})

This is just from the top of my head but I'd really would like to use the proper "register" for rules rather than importing them as methods all over

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.