• i7_388268
  • 42.4KB
  • zip
  • 0
  • VIP专享
  • 0
  • 2022-06-07 04:28
React形式钩 用于简单而强大的表单挂钩,具有验证支持和简单的国际化。 安装 npm install --save re-use-form 用法 输入先决条件 re-use-form提供了一个useForm挂钩,旨在与自定义Input组件一起使用。 Input是使用以下三个属性的任何组件: value , error和onChange (请注意,表单的助手也提供name属性供输入)。 它还必须将其value作为props中提供的onChange函数的第一个参数提供(有关更多信息和示例,请参见下面的“自定义onChange输入处理程序”部分)。 useForm挂钩 useForm钩子是程序包提供的主要钩子。 它接受一个可选的配置对象,该对象可用于指定表单的初始属性,客户端验证(请参见下面的“表单验证”部分),并通过提供默认验证选项来简化错误消息的国际化。 import { useForm
React Form Hook =============== Simple and robust form hook for [React]( with validation support and simple internationalization. [![build status](]( [![npm version](]( ## Installation ``` npm install --save re-use-form ``` ## Usage ### Input Prerequisites `re-use-form` provides a `useForm` hook that is intended to be used alongside with custom **Input** components. An **Input** is any component that consumes three properties: `value`, `error` and `onChange` (note that there is also `name` property supplied for input by form's helpers). It also has to provide it's `value` as first argument to `onChange` function supplied in props (see "Custom `onChange` Input Handler" section bellow for more info and examples). ### `useForm` Hook `useForm` hook is primary hook provided by the package. It accepts an optional configuration object that can be used to specify form's initial attributes, client-side validations (see *"Form Validations"* section bellow) and to ease internationalization of error messages by providing default validation options. ```js import { useForm } from 're-use-form'; import { TextField, Select } from 'my-components/inputs'; function MyForm({ onSave }) { const { input, attrs } = useForm(); // initializes form attributes with empty object. const save = () => onSave(attrs); return ( <> <TextField {...input('email')} label="Email" /> <TextField {...input('fullName')} label="Full Name" /> <Select {...input('address.countryId')} options={countryOptions} label="Country" /> <TextField {...input('')} label="City" /> <TextField {...input('address.line')} label="Address" /> <button onClick={save}>Submit</button> </> ); } ``` #### Note on `$` alias for `input` helper. `useForm` hook returns an object that has both `input` and `$` properties with the same value. While `input` is more explicit name, it might become cumbersome to use it over and over again. For this reason, `useForm` hook also provides a `$` helper that does the same. Basically, it's the same approach as used in [`react-form-base`]( package. All examples bellow will use `$` helper method as more common one. Keep in mind that although `$` is available by default, you can use any alias you find convenient when destructuring form helpers object returned by hook: ```js const { input: inp } = useForm(); // and then you can use `<Input {...inp('name')} />` ``` ### Hook Config `useForm` hook accepts a config as it's only argument. This `config` object is used to specify form's initial values, client-side validations (see *"Form Validations"* section bellow), their dependencies, etc. This config object **is memoized with no dependencies by default**. For dynamic configuration one should use `useConfig` hook (see bellow). Bellow are examples of `useForm` hook call with different config examples: ```js const { $ } = useForm({ initial: { username: '', items: [{}] }, validations: { username: 'presence' } }); ``` In cases when validation setup needs to share common options for all validation rules (like for internationalizing error messages, see corresponding section bellow), you can specify `defaultOptions` within validation setup: ```js const { t } = useTranslation('common'); const { $ } = useForm({ validations: { defaultOptions: { t }, rules: { username: 'presence' } } }); ``` To apply a dynamic configuration, for instance, input value-dependent validation, one can use `useConfig` helper hook. It has the same signature as `useMemo` hook, and should it's function provide a config object, it will be merged with the configuration form already has: ```js const { $, useConfig, attrs: { guest } } = useForm({ initial: { username: '', address: '', guest: false } }); useConfig(() => { return !guest && { validations: { username: 'presence', address: 'presence' } }; }, [guest]); ```` ### Custom `onChange` Input Handler The most common use-case when you need custom logic is to have custom onChange handler for handling any input's change. For this, `$`/`input` function takes this function as second attribute. This function will be called with input value as first argument and an object with meta information as second one. As a bare minimum, this object will have `name` property that corresponds to input's name (the string value passed to `$`/`input` function call), and other properties can be populated by your input components: ```js function TextField({ value, error, onChange, }) { const handleChange = useCallback((e) => { onChange(, { event: e }); }, []); return ( <div> <input value={value} onChange={handleChange} {} /> { error && <div className="error">{ error }</div> } </div> ); } function Form() { const { $, set } = useForm(); // uppercases user's input and logs event provided by TextField input component const changeInput = useCallback((value, { name, event }) => { console.log(event); set(name, value.toUpperCase()); }, []); return ( <> <TextField {...$('username', changeInput)} label="Username" /> <TextField {...$('address.postalCode', changeInput)} label="Postal Code" /> </> ); } ``` ### Purity Support All of the helper functions returned by `useForm` hook, with the exception of `get` and `getError` functions that depend on form attributes and errors whenever they change, are persistent and do not change on per render basis. The same goes for values returned by `$`/`input` helper - as long as on-change handler passed to `$` function is persistent (or if it was omitted), it's `onChange` property will be persistent as well, i.e. pure input components that consume it won't be re-rendered if other properties do not change too. If, for some reason, you want to disable input onChange handlers persistence, you can use `pureHandlers: false` config option. ### Note on Validation-less Forms Before we go to validation section bellow, it should be mentioned that even forms without defined client-side validation can use `getError`, `setErrors` and `setError` helpers returned by form hook. With no client-side validation, you might still want to interact with the server when user works with form and should something go wrong, you might want to set server-side errors for form's inputs and use them in form's rendering logic, which is exactly what mentioned helpers are about. ### Form Validations `re-use-form` provides a very easy way to declare form validations, which will automatically validate inputs on change when required. #### Vanilla JS Functions It is always possible to pass a function, or array of functions as input validation rule. Each validator function will be called with input value as first argument, and object of validation options as second one. By default, this object will have input `name` and `attrs` properties. This function should return an error if input's `value` doesn't pass validation logic: ```js function presence(value) { if (!value) return 'Cannot be blank'; } function UserForm() { const { $, validate } = useForm({ validations: { username: presence } }); // ... } ``` Since it's very common to have additional validation options, at least customizable message, the easiest way to achieve this is to have validator-generating functions that accept additional options and pass them to validator function they return: ```js function presence({ message }) { return (value) => { if (!value) { return message || 'Cannot be blank' } } } function format({ pattern, message }) { ret
    • npm
      npm install 编译和热重装以进行开发 npm run serve 编译并最小化生产 npm run build 运行测试 npm run test 整理和修复文件 npm run lint 运行单元测试 npm run test:unit 自定义配置 请参阅。
    • npm-max:NPM软件包
      最大NPM 该函数返回最大值 npm install
    • npm-exercises
    • npmTest:测试npm
      npmTest 测试npm
    • npm-lifecycle:npm生命周期脚本运行器
      npm v7发布后,将不建议使用此模块。 请不要绝对依赖它。 npm v7中使用的生命周期脚本运行程序是 。 请继续使用该模块。 npm-lifecycle 是一个独立的库,用于执行软件包的生命周期脚本。 它是从npm本身提取的,...
    • TSProjectDemo:npm ts
      TSProjectDemo:npm ts
    • npmd-install
      npmd 安装 从 npmd-resolve 树安装节点模块。 npm install - g npmd - resolve npmd - install npmd - resolve browserify | npmd - install 另外, 一个关键部分 执照 麻省理工学院
    • npm-cli-login
      npm-cli-login 允许您不使用STDIN,STDOUT登录到NPM。 在CI构建系统等地方使用。 还可以在〜/ .npmrc文件中创建/修改条目以进行身份​​验证。 安装 npm install -g npm-cli-login 使用-g标志通过CLI使用npm-cli-...
    • npm-practice
    • npm:测试
      npm 测试