@aaronuu/react-forms 中文文档教程
@aaronuu/react-forms
WIP 自述文件 - 一些功能尚未记录
Features
字段优先表单状态管理 - 字段和外部容器内的状态更新没有双重处理。
仅处理状态管理和棘手的反应形式怪癖,将视图和布局留给您。
Getting Started
Installing
使用 yarn
yarn add @aaronuu/react-forms
安装 使用 npm 安装
npm i @aaronuu/react-forms
Usage
@aaronuu/react-forms
有两种不同的使用方式
withForm({ name: 'form', ...config })
- a higher order component that will inject the forms state<ReactForms />
- a react component with a render prop (recommended)
withForm()
只是
将根据您在配置对象中提供的名称命名您的表单(默认为 form
)
@aaronuu/react-forms
中有四个不同的组件>
<ReactForms />
<Form />
<Field />
<FieldArray />
除了这些之外,还有两个不同的 HOC。
withForm({ ...config })
withContext
ReactForms
这是表单的状态容器,它是组织所有
状态和实现提交功能的地方。 该组件为您提供表单状态和访问表单助手以操纵该状态。
Props
asyncValuesReady: boolean (true)
有时您希望在加载一些将用作表单初始值的异步数据之前呈现表单。 当此道具从 false 切换为 true 时,它会重置表单并使用您传入的新初始值再次呈现。最好在此道具为真之前不允许用户输入表单,因为一切他们已经进入的将丢失。
initialValues: { [fieldName]: value }
整个表单的初始值,由每个字段名称键入。 各个字段的 initialValue
属性将优先于此对象中给出的值。
validateOnMount: boolean (false)
是否在安装字段时运行验证。
validateOnChange: boolean (true)
字段值更改时是否运行验证。
validateOnBlur: boolean (true)
当字段模糊时是否运行验证。
touchOnMount: boolean (false)
该字段在安装时是否被视为已触及。 这与 validateOnMount
属性和 isValid
状态配合使用效果很好,可以在表单挂载时验证表单,不显示任何错误,而是禁用按钮。
touchOnChange: boolean (true)
值更改时是否认为任何字段被触及。
touchOnBlur: boolean (true)
模糊时是否认为任何字段被触摸。
shouldUnregister: boolean (true)
每个字段在名称更改或卸载时是否应自行注销。 个别字段的 shouldUnregister
属性将优先于此。
handleSubmit: (values, actions) => Promise|void (noop)
提交表单或调用 submitForm
函数并且所有验证都已通过时将运行的函数。 如果此函数返回一个承诺 isSubmitting
将在该承诺已解决或拒绝后设置为 false,否则它将在完成执行后立即设置。
validate: (values) => Promise|Object
将用于验证每个字段的函数。 可以返回解析为字符串对象的承诺,以字段名称为键(表示对该字段的验证失败)或只是一个以字段名称为键的普通字符串对象。
Form
这是一个方便的组件,它将表单的 submitForm
方法附加到
Props
HTML5
Field
这是大部分工作发生的地方,所有
组件本身都是独立的状态管理器,只会将它们的状态传递给父 onBlur
(或 onChange
如果 sendImmediate
属性设置为 true)。 这些
应该被认为是它们自己的表单状态片段的真实来源。
每个
都在挂载时注册到它最近的表单容器,默认情况下在卸载时未注册(由 shouldUnregister
属性更改)。 此注册向表单容器发送
的初始状态及其单独的状态操作和验证方法,而注销则删除父容器状态中的字段条目。
在大多数情况下,您会希望取消注册
,因为它们已卸载,以免多余的条目污染状态,但是在某些情况下,保留该值可能是有利的大约。 例如,具有多个阶段的登录表单,通过实际卸载
而不是仅仅隐藏它,您将获得名义上的性能改进。
这些条目还将运行它们的验证方法,这可以停止提交表单而不向用户显示任何内容,因为错误应该附加到的字段现在已经消失。 解决此问题的最佳方法是确保在卸载字段之前验证通过,或者使用动态验证方法根据可见内容更改要验证的字段。
Props
name: string
- required
为字段指定的名称是与该字段交互的关键。 它是所有状态的关键,也是所有单独的 setField
方法的第一个参数。
这是唯一需要的道具。
initialValue: any ('')
这是
的初始值,默认为空字符串,以使文本输入用例更简单。
sendImmediate: boolean (false)
这会将状态发送到父容器 onChange
以及 onBlur
。
shouldUnregister: boolean (true)
当名称更改或卸载时,此特定字段是否会自行注销。
validate: Function
验证字段时将运行的函数应返回一个字符串(错误消息)以指示验证失败,或返回一个错误值以指示通过验证。
每次执行验证时都会运行此函数和父 validate
函数,只有在单个字段验证返回假值时才会使用父 validate
结果。
children: Function
渲染道具将被渲染并传递所有特定领域的道具和动作,供用户决定如何处理它们。
render: Function
与 children
相同
Component: React Component/Element/String: ('input')
将呈现并提供所有字段特定道具/操作(id、名称、值、onFocus、onChange、onBlur)的组件。 这具有最后的优先级,只有在 render 和 children 和 undefined 时才应该给出。
onFocus: Function (noop)
将传递反应事件并将在内部 onFocus
逻辑之前运行的函数。
onChange: Function (noop)
将传递反应事件并将在内部 onChange
逻辑之前运行的函数。
onBlur: Function (noop)
将传递反应事件并将在内部 onBlur
逻辑之前运行的函数。
Example
import React, { Component } from 'react';
import { ReactForms } from '@aaronuu/react-forms';
class FormContainer extends Component {
render() {
return (
<ReactForms
validate={values => {
if (!values.password) {
return { password: 'Password is required' };
}
return {};
}}
>
{({
values,
touched,
errors,
isDirty,
isValid,
setValues,
setFieldValue,
setErrors,
setFieldError,
setTouched,
setFieldTouched,
setStatus,
resetForm,
submitForm
}) => {
return (
<Fragment>
<Form>
<Field
name="email"
initialValue="new@email.com"
validate={value => {
if (value !== /email_regex/) {
return 'Invalid email';
}
return null;
}}
/>
<Field name="password" />
<button>Submit</button>
</Form>
</Fragment>
);
}}
</ReactForms>
);
}
}
Props
Caveats
提交表单时,字段级验证器和表单级验证器都将运行,只有在字段级错误返回错误值时才会应用表单级错误
Authors
- Aaron Williams - aaronnuu
License
该项目根据 MIT 许可证获得许可 - 请参阅 LICENSE.md 文件获取详细信息
@aaronuu/react-forms
WIP README - Some features are not documented yet
Features
Field first form state management - no double handling of state updates within fields and the outer container.
Deals with state management and tricky react form quirks only, leaves the view and layout up to you.
Getting Started
Installing
Install using yarn
yarn add @aaronuu/react-forms
Install using npm
npm i @aaronuu/react-forms
Usage
There are two different ways to use @aaronuu/react-forms
withForm({ name: 'form', ...config })
- a higher order component that will inject the forms state<ReactForms />
- a react component with a render prop (recommended)
withForm()
is just a light wrapper around <ReactForms />
that will namespace your form based on the name you give within the configuration object (default is form
)
There are four different components within @aaronuu/react-forms
<ReactForms />
<Form />
<Field />
<FieldArray />
In addition to these there are two different HOC's
withForm({ ...config })
withContext
ReactForms
This is the state container for the form, it is the place where all <Field />
state is organised and the submit functionality is implemented. This component gives you the state of the form and access to the form helpers to manipulate that state.
Props
asyncValuesReady: boolean (true)
Sometimes you want to render a form before some asynchrounous data that will be used as the initial values of the form has been loaded. When this prop switches from false to true it resets the form and will render again with the new initial values that you have passed in. It is best to not allow users to be able to input into the form until after this prop is true as everything that they have already entered will be lost.
initialValues: { [fieldName]: value }
The initial values for the whole form, keyed by each fields name. Individual fields' initialValue
prop will take precedence over the value given in this object.
validateOnMount: boolean (false)
Whether or not to run validations when the field is mounted.
validateOnChange: boolean (true)
Whether or not to run validations when the field value changes.
validateOnBlur: boolean (true)
Whether or not to run validations when the field is blurred.
touchOnMount: boolean (false)
Whether or not the field is considered touched when it mounts. This works well with the validateOnMount
prop and isValid
state to validate a form as it mounts, not show any errors but disable a button.
touchOnChange: boolean (true)
Whether or not any field is considered to be touched when it's value changes.
touchOnBlur: boolean (true)
Whether or not any field is considered touched when it is blurred.
shouldUnregister: boolean (true)
Whether each field should unregister itself when it's name changes or it is unmounted. Individual fields' shouldUnregister
property will take precendence over this.
handleSubmit: (values, actions) => Promise|void (noop)
The function that will run when the form is submitted or when the submitForm
function is called, and all validations have passed. If this function returns a promise isSubmitting
will be set to false after that promise has resolved or rejected, otherwise it will be set immediately after it has finished executing.
validate: (values) => Promise|Object
The function that will be used to validate each field. Can either return a promise that resolves to an object of strings, keyed by the field name (indicating a failed validation for that field) or just a plain object of strings keyed by the field name.
Form
This is a convenience component that attaches the form's submitForm
method onto a <form />
's onSubmit
handler.
Props
Anything that a HTML5 <form />
takes.
Field
This is where most of the work happens, all <Field />
components are self contained state managers in their own right and will only pass their state up to the parent onBlur
(or onChange
if the sendImmediate
prop is set to true). These <Field />
's should be considered to be the source of truth for their own slice of the form state.
Each <Field />
is registered with it's closest form container on mount and by default is unregistered when unmounting (changed by the shouldUnregister
prop). This registration sends the form container the initial state of the <Field />
as well as it's individual state manipulation and validation methods, while the unregistration deletes the field entry in the parent container's state.
In most cases you will want be unregistering <Field />
's as they are unmounted to not pollute the state with entries that are superfluous, however in certain situations it can be advantageous to keep the value around. For example, login forms with multiple stages, you will get a nominal performance improvement by actually unmounting the <Field />
instead of just hiding it.
These entries will also have their validation methods run which could stop the form from submitting without showing anything to the user as the field the error should be attached to is now gone. The best way around this is to make sure the validation passes before unmounting the field, or by having a dynamic validation method that changes what fields are validated based on what is visible.
Props
name: string
- required
The name given to a field is the key to interacting with that field. It is the key for all of it's state and also the first argument given to all of the individual setField
methods.
This is the only prop that is required.
initialValue: any ('')
This is the initial value of the <Field />
defaulted to an empty string to make the text-input use case simpler.
sendImmediate: boolean (false)
This sends state up to the parent container onChange
as well as onBlur
.
shouldUnregister: boolean (true)
Whether or not this particular field will unregister itself when it's name changes or it unmounts.
validate: Function
Function that will be run when the field is being validated, should return a string (the error message) to indicate failed validation, or a falsey value to indicate passed validation.
Both this function and the parent validate
function will be run every time validation is performed, with the parent validate
result only being used if the individual field validation returns a falsey value.
children: Function
The render prop that will be rendered and passed all field specific props and actions for the user to decide what to do with them.
render: Function
Same as children
Component: React Component/Element/String: ('input')
The component that will be rendered and given all of the field specific props / actions (id, name, value, onFocus, onChange, onBlur). This takes the last priority and should only be given if render and children and undefined.
onFocus: Function (noop)
Function that will passed the react event and will run before the internal onFocus
logic.
onChange: Function (noop)
Function that will passed the react event and will run before the internal onChange
logic.
onBlur: Function (noop)
Function that will passed the react event and will run before the internal onBlur
logic.
Example
import React, { Component } from 'react';
import { ReactForms } from '@aaronuu/react-forms';
class FormContainer extends Component {
render() {
return (
<ReactForms
validate={values => {
if (!values.password) {
return { password: 'Password is required' };
}
return {};
}}
>
{({
values,
touched,
errors,
isDirty,
isValid,
setValues,
setFieldValue,
setErrors,
setFieldError,
setTouched,
setFieldTouched,
setStatus,
resetForm,
submitForm
}) => {
return (
<Fragment>
<Form>
<Field
name="email"
initialValue="new@email.com"
validate={value => {
if (value !== /email_regex/) {
return 'Invalid email';
}
return null;
}}
/>
<Field name="password" />
<button>Submit</button>
</Form>
</Fragment>
);
}}
</ReactForms>
);
}
}
Props
Caveats
When submitting the form both the field level validators and the form level validators will be run, with the form level errors only being applied if the field level error returns a falsey value
Authors
- Aaron Williams - aaronnuu
License
This project is licensed under the MIT License - see the LICENSE.md file for details