import React, { useCallback, useEffect, useState } from 'react' import { observer } from 'mobx-react' import { FormState, FieldState, bindInput, ComposibleValidatable } from 'formstate-x' import { Form, FormItem, FormItemProps, TextInput, PasswordInput } from 'react-icecream' // 构造 form state 的逻辑 function createFormState() { const passwordField = new FieldState('').validators(notEmpty) const password2Field = new FieldState('').validators( notEmpty, (v: string) => v !== passwordField.value && '密码不一致' ) return new FormState({ username: new FieldState('').validators(notEmpty), password: passwordField, password2: password2Field }) } function notEmpty(v: string) { return v.trim() === '' && '不可为空' } export default observer(() => { const state = useFormState(createFormState) const handleSubmit = useCallback(async () => { const validated = await state.validate() if (validated.hasError) return alert(`Submit with: ${state.value.username}:${state.value.password}`) }, [state]) return (
) }) // 在 react 组件中使用 formstate-x 的 hook function useFormState(createState: () => ComposibleValidatable) { const [state] = useState(createState) useEffect(() => () => state.dispose(), [state]) return state } // 将 formstate-x state 绑定到 icecream FormItem 的辅助函数 function bindFormItem(state: ComposibleValidatable): Pick { if (state.hasError) { return { validateStatus: 'error', validateMessage: state.error } } if (state.validated) { return { validateStatus: 'success' } } return { validateStatus: 'default' } }