11import { KeyType , InnerMethodsReturnType } from '../types' ;
22import { useState } from 'react' ;
3+ import { useValidator } from '@validator.tool/hook' ;
34
45type State < FormData = any > = {
56 store : Partial < FormData > ;
67 initialValues : Partial < FormData > ;
7- errorMessages : Partial < Record < string , string > > ;
88} ;
99
1010export default function useForm <
@@ -14,40 +14,65 @@ export default function useForm<
1414> ( ) : any {
1515 const [ state , setState ] = useState < State > ( {
1616 initialValues : { } ,
17- errorMessages : { } ,
1817 store : { } ,
1918 } ) ;
2019
21- const updateStore = ( datas : any ) => {
20+ const { validator, forceUpdate } = useValidator ( {
21+ initValues : { initialValues : state . initialValues } ,
22+ } ) ;
23+
24+ const updateStore = ( datas : Partial < any > ) => {
2225 setState ( {
2326 ...state ,
2427 ...datas ,
2528 } ) ;
2629 } ;
2730
28- const innerUseValidator = ( ) => { } ;
29-
31+ // 获取表单字段的值
3032 const getFieldValue = ( field : FieldKey ) : FieldValue => {
3133 const { store } = state ;
3234 return store [ field ] ;
3335 } ;
3436
37+ // 设置表单字段的值
38+ const setFieldValue = ( field : FieldKey , value : FieldValue ) => {
39+ updateStore ( {
40+ store : {
41+ ...state . store ,
42+ [ field ] : value ,
43+ } ,
44+ } ) ;
45+ } ;
46+
47+ // 重置表单
48+ const resetFieldValue = ( ) => {
49+ updateStore ( {
50+ store : { ...state . initialValues } ,
51+ } ) ;
52+ } ;
53+
3554 const getStore = ( ) : Partial < FormData > => {
3655 const { store } = state ;
3756 return store ;
3857 } ;
3958
4059 const getFormInstance = ( ) => {
4160 return {
61+ forceUpdate,
62+ validator,
4263 getStore : getStore ,
4364 getFieldValue : getFieldValue ,
65+ setFieldValue : setFieldValue ,
66+ resetFieldValue,
4467 getInnerMethods : ( inner ?: boolean ) : InnerMethodsReturnType < FormData , FieldValue , FieldKey > => {
4568 let methods = { } as any ;
4669 if ( inner ) {
4770 methods = {
4871 store : state . store ,
4972 initialValues : state . initialValues ,
5073 updateStore : updateStore ,
74+ validator,
75+ forceUpdate,
5176 } ;
5277 }
5378 return methods ;
0 commit comments