1.7.0 • Published 2 months ago

@alifd/field v1.7.0

Weekly downloads
1,125
License
MIT
Repository
github
Last release
2 months ago

Field

  • category: Components
  • family: DataEntry
  • chinese: 表单辅助工具
  • cols: 1
  • type: 表单

Development Guide

When to use

Fields can be used to manage data when it comes to form data manipulation and validation. After being associated with a component, the form data can be automatically written back, read, and verified.

Use caution

  • With Field init components, value onChange must be placed in init's third argument, otherwise it may be overridden by init.
  • Form has been deeply optimized with Field for data acquisition and automatic verification prompt. It is recommended to use Field in Form. Please check Form demo.
  • initValue The defaultValue of a similar component, which only takes effect when the component first renders (the ajax asynchronous invocation setting initValue may have missed the first render)
  • with parseName=true you could use getValues to get a struct value, but not work in getValue you still need pass complete key

basic use

Class Demo extends React.Component {
    Field = new Field(this); // instance creation

    onClick = ()=>{
        Console.log(this.field.getValue('name'));
    }
    Render() {
        Const init = this.field.init;

        // Note: initValue will only be assigned when the component is first initialized. If you are using an asynchronous assignment, use setValue
        Return <div>
            <Input {...init('name',{initValue:'first value'})} />
            <button onClick={this.onClick>Get Data</button>
        </div>
    }
}

update data

Event Updates

Class Demo extends React.Component {
    Field = new Field(this);

    onClick = ()=>{
        this.field.setValue('name', 'newvalue'); // Assignment will automatically trigger render
    }
    Render() {
        Const init = this.field.init;

        Return <div>
            <Input {...init('name')} />
            <button onClick={this.onClick}>Settings</button>
        </div>
    }
}

props update

Class Demo extends React.Component {
    Field = new Field(this);

    // Set the data before the component is mounted (this can be replaced with initValue)
    componentWillMount() {
        this.field.setValue('name', 'init Name')
    }
    // Receive data from props
    componentWillReceiveProps(nextProps) {
        this.field.setValue('name', nextProps.name)
    }
    Render() {
        Const init = this.field.init;

        Return <div>
            <Input {...init('name')} />
        </div>
    }
}

ajax update

Class Demo extends React.Component {
    Field = new Field(this);

    onClick = ()=>{
        Ajax({
            Url:'/demo.json',
            Success:(json)=>{
                // Update of assignment in callback event
                this.field.setValue('name',json.name);
            }
        });
    }
    Render() {
        Const init = this.field.init;

        Return <div>
            <Input {...init('name')} />
            <button onClick={this.onClick}>Settings</button>
        </div>
    }
}

onChange update monitoring

Two usages: 1. Unified management

Class Demo extends React.Component {
    Field = new Field(this,{
        onChange:(name, value) => {
          Switch(name) {
            Case 'name1':
              this.field.setValue('name2','value set by name1');
              Break;
            Case 'name2':
              this.field.setValue('name1','value set by name2');
              Break;
          }
        }
    });
    Render() {
        Const init = this.field.init;

        Return <div>
          <Input {...init('name1')} />
          <Input {...init('name2')} />
        </div>
    }
}
  1. Individual management
Class Demo extends React.Component {
    Render() {
        Const init = this.field.init;

        Return <div>
          <Input {...init('name1',{
              Props:{
                onChange:(v)=>{
                  this.field.setValue('name2','value set by name1');
                }
              }
            })} />
          <Input {...init('name2',{
              Props:{
                onChange:(v)=>{
                  this.field.setValue('name1','value set by name2');
                }
              }
            })} />
        </div>
    }
}

For details, please check Demo Demo Associate Control

API

initialization

Let myfield = new Field(this [,options]);
ParameterDescriptionTypeOptionalDefault
thisThe incoming call to this classReact.Componentmust be set
optionsSome event configuration, detailed parameters are as followsObjectNot required

options configuration item

ParametersDescriptionTypeDefault
onChangeall component changes will arrive here setValue won't trigger the functionFunction(name,value)
parseNameWhether to translate name in init(name) (getValues ​​will convert a string with . to an object)Booleanfalse
forceUpdateOnly the components of PureComponent are recommended to open this forced refresh function, which will cause performance problems (500 components as an example: the render will cost 700ms when it is turned on, and 400ms if it is turned off)Booleanfalse
scrollToFirstErrorscrolling field.validate scrolls to the first errored component, offsets if it is an integerBoolean/Numbertrue
autoUnmountAutomatically delete the Unmout element, if you want to keep the data can be set to falseBooleantrue
autoValidateAutomatically validate while value changedBooleantrue
valuesinitial valueObject
processErrorMessagefunction to transform error objects on validation. Main usage is to add key prop to React componentFunction(error)
afterValidateRerenderfunction to perform any operations after components have rerendered to show validation results.Function({errorGroup, options, instance}) - see afterValidateRerender for more information

API Interface

The api interface provided by the object after new (eg myfield.getValues()) (The api function starting with set should not be manipulated in render, which may trigger an infinite loop)

ParameterDescriptionTypeOptionalDefault
initInitialize each component, Detailed Parameters below)Function(name:String, option:Object)
getValues ​​Get the value of a group of input controls. If no parameters are passed, get the values ​​of all componentsFunction([names: String[]])
getValueget the value of a single input controlFunction(name: String)
setValues ​​Sets the value of a set of input controls (triggers render, follow the use of react time)Function(obj: Object)
setValueSets the value of a single input control (triggers render, follow the use of react time)Function(name: String, value)
validateCallbackValidate and retrieve the values ​​of a set of input fields and Error.Function([names: String[]], options: Object, callback: Function(errors, values))
validatePromiseValidate and retrieve the values ​​of a set of input fields and Error. Returns a promiseFunction([names: String[]], options: Object, (optional) callback: Function(errors, values))
getErrorGet Error of a Single Input ControlFunction(name: String)
getErrorsGet Errors of a Group of Input ControlsFunction(name: String)
setErrorSet Error for a Single Input ControlFunction(name: String, errors:String/ArrayString)
setErrorsSet Errors of a Group of Input ControlsFunction(obj: Object)
resetreset the value of a group of input controls, clear the checksumFunction([names: String[]])
resetToDefaultResets the value of a group of input controls to the defaultFunction([names: String[]])
getStateJudge check statusFunction(name: String)'error' 'success' 'loading' ''''
getNamesGet the key of all componentsFunction()
removeDelete the data of a certain control or a group of controls. After deletion, the validate/value associated with it will be cleared.Function(name: String/String[])
spliceArraydelete data of name like name.{index}Function(keyMatch: String, index: Number)
watchwatch field value changesFunction(names: String[], value: unknown, oldValue: unknown, triggerType: 'init''change''setValue''unmount''reset')

init

init(name, options, props)
ParameterDescriptionTypeOptionalDefault
nameRequired unique input control symbolString
options.valueNameattribute name of the component value, such as Checkbox is checked, Input is valueString'value'
options.initValueThe initial value of the component (the component will be read only when rendering for the first time, and later modifying this value is invalid), similar to defaultValueany
options.triggerName of the event that triggered the data changeString'onChange'
options.rulesChecksum RulesArray/Object
options.getValueFormattercustom way to get value from onChange event, Detailed usage see demo custom data getFunction(value, ...args) parameter order and components are exactly the same The
options.getValueFormattercustom way to set value. Detailed usage see demo custom data getFunction(values)
propsComponent-defined events can be written hereObject
autoValidateAutomatically validate while value changedBooleantrue

return

{id,value,onChange}

rules

{
    rules:[{ required: true }]
}

multiple rule

{
    rules:[{required:true,trigger:'onBlur'},{pattern:/abcd/,message:'match abcd'},{validator:(rule, value, callback)=>{callback('got error')}}]
}
ParameterDescriptionTypeOptional
requiredcannot be emptyBooleantrueundefined/null/"/[] will trigger this rule)
patterncheck regular expressionregular
minLengthMinimum string length / Minimum number of arraysNumberString/Number/Array
maxLengthMaximum length of string / Maximum number of arraysNumberString/Number/Array
lengthstring exact length / exact number of arraysnumberString/Number/Array
minMinNumberString/Number
maxmaximumNumberString/Number
formatsum of common patternsStringurl, email, tel, numberString
validatorCustom validation, (don't forget to execute callback() when validation is successful, otherwise validation will not return)Function(rule,value,callback)
triggerName of the event that triggered the checkString/ArrayonChange/onBlur/...onChange
messageerror messageString

Custom Component Access to Field Standards

  • Supports controlled mode (value+onChange) Must      - value control component data display      - onChange callback function when the component changes (the first parameter can be given to value)

  • One complete operation throws an onChange event      For example, there is a process that indicates the status of the progress, it is recommended to increase the API onProcess; if there is a Start indicates the startup state, it is recommended to increase the API onStart

  • Clear data when value={undefined}, field's reset function will send undefined data to all components

componentWillReceiveProps(nextProps) {
    if ('value' in nextProps ) {
        this.setState({
           value: nextProps.value === undefined? []: nextProps.value   //  set value after clear
        })
    }
}

afterValidateRerender

afterValidateRerender receives an object with the following properties

ParameterDescriptionType
errorsGroupMap of field elements with errors, indexed by name. Access the error by errorsGroup[field_name].errorsObject
optionsfield's options propertyObject
instancefields's instance property, which holds references to React components for the field itemsObject

Known Issues

  • Why doesn't the callback function enter the this.field.validate manually? A: Is it safe to define the validator method to ensure that the callback can be executed on any branch?
2.0.0

2 months ago

1.7.0

5 months ago

1.6.8

5 months ago

1.6.7

5 months ago

1.6.6

6 months ago

1.6.5

6 months ago

1.6.4

6 months ago

1.6.4-beta.0

6 months ago

1.6.3

7 months ago

1.6.3-beta.0

7 months ago

1.6.2

1 year ago

1.6.1

1 year ago

1.6.0

2 years ago

1.5.9-beta.1

2 years ago

1.5.9-beta

2 years ago

1.5.8

2 years ago

1.5.7

2 years ago

1.5.6

2 years ago

1.5.5

3 years ago

1.5.4

3 years ago

1.5.3

3 years ago

1.5.2

3 years ago

1.5.1

3 years ago

1.5.0

3 years ago

1.4.6

3 years ago

1.4.5

4 years ago

1.4.4

4 years ago

1.4.3

4 years ago

1.4.2

4 years ago

1.4.1

4 years ago

1.4.0

4 years ago

1.3.5

4 years ago

1.3.4

4 years ago

1.3.3

5 years ago

1.3.2

5 years ago

1.3.1

5 years ago

1.3.0

5 years ago

1.2.1

5 years ago

1.1.9

5 years ago

1.1.8

5 years ago

1.2.0

5 years ago

1.1.7

5 years ago

1.1.6

5 years ago

1.1.5

5 years ago

1.1.4

5 years ago

1.1.3

5 years ago

1.1.2

5 years ago

1.1.1

5 years ago

1.1.0

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago