https://github.com/postor/react-form
yet another solution for react forms | 又一个 react 表单的解决方案
https://github.com/postor/react-form
Last synced: 3 months ago
JSON representation
yet another solution for react forms | 又一个 react 表单的解决方案
- Host: GitHub
- URL: https://github.com/postor/react-form
- Owner: postor
- License: mit
- Created: 2022-03-22T11:21:24.000Z (almost 4 years ago)
- Default Branch: main
- Last Pushed: 2022-07-19T07:33:10.000Z (over 3 years ago)
- Last Synced: 2025-01-25T17:45:40.446Z (11 months ago)
- Language: TypeScript
- Size: 1.04 MB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# @postor/react-form
yet another solution for react forms | 又一个 react 表单的解决方案

https://codesandbox.io/s/pedantic-black-y92k7k?file=/src/App.tsx:81-99
## why another | 为何要另起炉灶?
- zero dependency | 无依赖
- no prop drilling, contexed | 使用 contex,避免 prop drilling
- no define all fields ahead, define field where is used | 无需提前定义所有字段,在对应字段的组件中定义即可
- no ui/element | 没有界面和HTML元素
- cross platform (web & RN) | 跨平台,web 和 RN 通用
- easy api | 简单易懂的接口
## usage | 使用
```
import {Provider,Consumer} from '@postor/react-form'
...
{({
formData,
validatingFields,
errorFields,
untouchedFields,
register
}) => (
{(() => {
let { value, setValue, error, touched, validating } = register(
"account",
{
validate: async (val) => {
if (val.length < 2) throw `name length at least 2`;
if (val.length > 6) throw `name length at most 6`;
if (await exists(val)) throw `name already exists`;
}
}
);
console.log({ value, error, touched, validating });
return (
setValue(e.target.value)}
placeholder="enter account"
/>
{validating ? (
validating...
) : touched && error ? (
{error}
) : null}
);
})()}
{(() => {
if (validatingFields.length) {
return (
{`${validatingFields.join(",")} validating`}
);
} else if (errorFields.length) {
return {`${errorFields.join(",")} error`};
} else {
return (
alert(JSON.stringify(formData))}>
submit
);
}
})()}
)}
...
```