import React, { useCallback } from 'react' import { FormState, FieldState, ValueOf } from 'formstate-x' import { observer } from 'mobx-react' import { Form, FormItem, useFormstateX, TextInput, PasswordInput, RadioGroup, Radio, Checkbox, MultiSelect, SelectOption } from 'react-icecream/form-x' type AccountType = 'default' | 'enterprise' // 构造表单状态 function createFormState() { const accountTypeField = new FieldState('default') const usernameField = new FieldState('').validators(notEmpty) const passwordField = new FieldState('').validators(notEmpty) const password2Field = new FieldState('').validators( notEmpty, (v: string) => v !== passwordField.value && '密码不一致' ) const productsField = new FieldState([]).validators( products => productsRequired(accountTypeField.value) && products.length === 0 && '不可为空' ) const agreedField = new FieldState(false).validators( agreed => !agreed && '请勾选' ) return new FormState({ accountType: accountTypeField, username: usernameField, password: passwordField, password2: password2Field, products: productsField, agreed: agreedField }) } // 表单中值的类型 type Value = ValueOf> export default observer(() => { const state = useFormstateX(createFormState, []) const handleSubmit = useCallback((value: Value) => { console.log(`Submit with: ${JSON.stringify(value)}.`) return new Promise(resolve => setTimeout(resolve, 2000)) }, []) const handleCancel = useCallback(() => ( console.log('Cancelled.') ), []) return (
普通账号 企业账号 {productsRequired(state.$.accountType.value) && ( 对象存储 Kodo CDN 智能多媒体服务 Dora 云主机服务 QVM 机器数据分析平台 Pandora )}
) }) function productsRequired(accountType: AccountType) { return accountType === 'enterprise' } function notEmpty(v: string) { return v.trim() === '' && '不可为空' }