rc-form(翻譯)

原地址:https://npm.taobao.org/package/rc-formnode

rc-form

React 高階表單控制組件。react

NPM version build status Test coverage gemnasium deps node version npm download

開發

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

特徵

安裝

rc-form

使用

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);

 react native使用

更多用法預覽git

 查看源碼github

或者更輕快的用法:chrome

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.validateMessages async-validator的預置消息 Object {}
option.onFieldsChange 當字段名改變時調用, 能夠dispatch字段到redux store. (props, changed, all): void NOOP
option.onValuesChange 當值改變時調用 (props, changed, all): void NOOP
option.mapProps 獲取新的props 並轉移到 WrappedComponent組件. (props): Object props => props
option.mapPropsToFields 將值從props 轉換爲字段. 用於redux store的可讀字段. (props): Object NOOP
option.fieldNameProp 存儲 getFieldProps 的 name 參數. String -
option.fieldMetaProp 存儲 getFieldProps 的元數據(meta data). String -
option.fieldDataProp 存儲字段值 String -
option.withRef(deprecated) 維持wrapped component實例的ref,使用  refs.wrappedComponent  訪問. boolean false

注意:在rc-form@1.4.0以後使用WrdabdCysEclipse代替ReffRef 

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

createForm()的返回函數. 它將以prop 的形式傳遞一個對象,並將下列成員傳遞給WrappedComponent:npm

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

這將建立一個prop值,該值能夠設置在支持值和onChange接口的input或InputComponent上。redux

設置以後,將在input上建立一個binding。react-native

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

name: String

該input的惟一名稱。app

option: Object

選項 描述 類型 默認值
option.valuePropName 組件的值的字段的prop名稱,例如:checkbox的設置是checked String 'value'
option.getValueProps 經過字段值獲取組件的props. (value): Object (value) => ({ value })
option.getValueFromEvent 指定如何從事件中獲取值。 (e): any See below
option.initialValue 當前組件的值的初始化。 any -
option.normalize 返回正常的值. (value, prev, all): Object -
option.trigger 監聽表單數據事件. String 'onChange'
option.validateTrigger 監聽校驗事件. 當只調用props.validateFields用於校驗的時候設置. String String[]
option.rules 校驗規則. 參考: async-validator Object[] -
option.validateFirst 是否中止對該字段的第一條錯誤規則進行校驗。 boolean false
option.validate   Object[] -
option.validate[n].trigger 監聽校驗事件. 當只調用props.validateFields用於校驗的時候設置. String String[]
option.validate[n].rules 校驗規則. 參考: async-validator Object[] -
option.hidden 在驗證或獲取字段時忽略當前字段 boolean false
getValueFromEvent的默認值
function defaultGetValueFromEvent(e) {
  if (!e || !e.target) {
    return e;
  }
  const { target } = e;
  return target.type === 'checkbox' ? target.checked : target.value;
}

 

提示
{
  validateTrigger: 'onBlur',
  rules: [{required: true}],
}
// is the shorthand of
{
  validate: [{
    trigger: 'onBlur',
    rules: [required: true],
  }],
}

 

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

與 getFieldProps類似, 可是增長了一些幫助warning信息,能夠直接在 React.Node props寫 onXX :dom

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

 

getFieldsValue([fieldNames: String[]])

經過fieldNames獲取字段值.

getFieldValue(fieldName: String)

經過fieldName獲取字段值.

getFieldInstance(fieldName: String)

經過字段名稱獲取字段的公共實例。

setFieldsValue(obj: Object)

經過 kv object設置字段值.

setFieldsInitialValue(obj: Object)

經過KV對象設置字段初始值。用於重置和初始顯示/值。

setFields(obj: Object)

用KV對象設置字段。每一個字段的內容均可以包含錯誤信息和值。

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

經過fieldNames校驗並獲取字段值.

async-validator的校驗方法相同. 而且增長  force  and  scroll .  scroll   dom-scroll-into-view's 函數參數  config 相同.

options.force: Boolean

默認爲false. 是否校驗已經校驗過的字段(由ValueTebug觸發)。

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

獲取input的校驗錯誤信息.

getFieldError(name): String[]

獲取input的校驗錯誤信息.

isFieldValidating(name: String): Bool

該input是否已校驗。

isFieldsValidating(names: String[]): Bool

是否有一個input校驗。

isFieldTouched(name: String): Bool

這個input的值是否已經被用戶改變了。

isFieldsTouched(names: String[]): Bool

是否有一個input的值已經被用戶改變了。

resetFields([names: String[]])

重置指定的輸入。默認爲全部。

isSubmitting(): Bool (Deprecated)

表單是否已提交.

submit(callback: Function) (Deprecated)

因爲提交返回true,調用callback後,提交返回false。

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

createDOMForm 擴展, 支持props.form.validateFieldsAndScroll

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

props.form.validateFields 擴展, 支持滾動到第一個非法表單字段

options.container: HTMLElement

默認爲窗體字段的第一個滾動容器(直到文檔)。

注意

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

 

  • 不能對getFieldProps使用ref prop
<input {...getFieldProps('ref')} />

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

或者

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

 

測試用例

npm test
npm run chrome-test

範圍

npm run coverage

打開coverage/ dir

許可證

rc-form是在MIT許可下發布的。

 

原地址:https://npm.taobao.org/package/rc-form

相關文章
相關標籤/搜索