diff --git a/src/packages/form/__tests__/form.spec.tsx b/src/packages/form/__tests__/form.spec.tsx index 8a07b93e01..d5d3950501 100644 --- a/src/packages/form/__tests__/form.spec.tsx +++ b/src/packages/form/__tests__/form.spec.tsx @@ -2,6 +2,7 @@ import * as React from 'react' import { useEffect } from 'react' import { fireEvent, render, waitFor } from '@testing-library/react' import '@testing-library/jest-dom' +import { Button, Radio, Space } from '@nutui/nutui-react' import Form, { FormInstance } from '@/packages/form' import Input from '@/packages/input' @@ -312,3 +313,73 @@ test('no-style and render function', async () => { expect(relatedInput).toBeTruthy() }) }) + +test('useWatch', async () => { + const Demo = () => { + const [form] = Form.useForm() + const account = Form.useWatch('account', form) + const loginMethod = Form.useWatch('loginMethod', form) + return ( +
+
+
+ 你将使用 {loginMethod === 'mobile' ? '手机号' : '邮箱'}{' '} + {account} 登录 +
+ +
+ + } + > + + + + 手机号 + + 邮箱 + + + + + + <> + {loginMethod === 'mobile' && ( + + + + )} + {loginMethod === 'email' && ( + + + + )} + +
+ ) + } + + const { container } = render() + const clickTest = container.querySelector('.clickTest') + if (clickTest) { + fireEvent.click(clickTest) + const result = container.querySelector('.result') + expect(result).toHaveTextContent('你将使用 邮箱 123 登录') + } +}) diff --git a/src/packages/form/demo.taro.tsx b/src/packages/form/demo.taro.tsx index 3881c4d845..0076b72f6a 100644 --- a/src/packages/form/demo.taro.tsx +++ b/src/packages/form/demo.taro.tsx @@ -9,6 +9,7 @@ import Demo4 from './demos/taro/demo4' import Demo5 from './demos/taro/demo5' import Demo6 from './demos/taro/demo6' import Demo7 from './demos/taro/demo7' +import Demo8 from './demos/taro/demo8' const FormDemo = () => { const [translated] = useTranslate({ @@ -20,6 +21,7 @@ const FormDemo = () => { title4: 'Form.useForm 对表单数据域进行交互。', title5: '表单类型', validateTrigger: '校验触发时机', + useWatch: 'useWatch', }, 'en-US': { basic: 'Basic Usage', @@ -29,6 +31,7 @@ const FormDemo = () => { title4: 'Interact with form data fields via Form.useForm', title5: 'Form Type', validateTrigger: 'Validate Trigger', + useWatch: 'useWatch', }, }) @@ -50,6 +53,8 @@ const FormDemo = () => {

{translated.title5}

+

{translated.useWatch}

+ ) diff --git a/src/packages/form/demo.tsx b/src/packages/form/demo.tsx index effa42d77a..dfbcccd246 100644 --- a/src/packages/form/demo.tsx +++ b/src/packages/form/demo.tsx @@ -7,6 +7,7 @@ import Demo4 from './demos/h5/demo4' import Demo5 from './demos/h5/demo5' import Demo6 from './demos/h5/demo6' import Demo7 from './demos/h5/demo7' +import Demo8 from './demos/h5/demo8' const FormDemo = () => { const [translated] = useTranslate({ @@ -18,6 +19,7 @@ const FormDemo = () => { title4: 'Form.useForm 对表单数据域进行交互。', title5: '表单类型', validateTrigger: '校验触发时机', + useWatch: 'useWatch', }, 'en-US': { basic: 'Basic Usage', @@ -27,6 +29,7 @@ const FormDemo = () => { title4: 'Interact with form data fields via Form.useForm', title5: 'Form Type', validateTrigger: 'Validate Trigger', + useWatch: 'useWatch', }, }) @@ -47,6 +50,8 @@ const FormDemo = () => {

{translated.title5}

+

{translated.useWatch}

+ ) diff --git a/src/packages/form/demos/h5/demo8.tsx b/src/packages/form/demos/h5/demo8.tsx new file mode 100644 index 0000000000..4cec12da48 --- /dev/null +++ b/src/packages/form/demos/h5/demo8.tsx @@ -0,0 +1,64 @@ +import React from 'react' +import { Button, Form, Input, Radio, Space } from '@nutui/nutui-react' + +type FieldType = { account?: string; loginMethod?: 'mobile' | 'email' } + +const Demo8 = () => { + const [form] = Form.useForm() + const account = Form.useWatch('account', form) + const loginMethod = Form.useWatch('loginMethod', form) + + return ( +
+
+
+ 你将使用{loginMethod === 'mobile' ? '手机号' : '电子邮箱'} + {account}登录 +
+ +
+ + } + > + + + + 手机号 + 电子邮箱 + + + + + <> + {loginMethod === 'mobile' && ( + + + + )} + {loginMethod === 'email' && ( + + + + )} + +
+ ) +} + +export default Demo8 diff --git a/src/packages/form/demos/taro/demo8.tsx b/src/packages/form/demos/taro/demo8.tsx new file mode 100644 index 0000000000..ca743e2e13 --- /dev/null +++ b/src/packages/form/demos/taro/demo8.tsx @@ -0,0 +1,64 @@ +import React from 'react' +import { Button, Form, Input, Radio, Space } from '@nutui/nutui-react-taro' + +type FieldType = { account?: string; loginMethod?: 'mobile' | 'email' } + +const Demo8 = () => { + const [form] = Form.useForm() + const account = Form.useWatch('account', form) + const loginMethod = Form.useWatch('loginMethod', form) + + return ( +
+
+
+ 你将使用{loginMethod === 'mobile' ? '手机号' : '电子邮箱'} + {account}登录 +
+ +
+ + } + > + + + + 手机号 + 电子邮箱 + + + + + <> + {loginMethod === 'mobile' && ( + + + + )} + {loginMethod === 'email' && ( + + + + )} + +
+ ) +} + +export default Demo8 diff --git a/src/packages/form/doc.en-US.md b/src/packages/form/doc.en-US.md index ed414f760b..fa01e2fac5 100644 --- a/src/packages/form/doc.en-US.md +++ b/src/packages/form/doc.en-US.md @@ -58,6 +58,14 @@ import { Form } from '@nutui/nutui-react' ::: +### useWatch + +:::demo + + + +::: + ### Form Type :::demo @@ -121,7 +129,7 @@ The rule validation process is based on [async-validator](https://github.com/yim ### FormInstance -Form.useForm() creates a Form instance, which is used to manage all data states. +`Form.useForm()` creates a Form instance, which is used to manage all data states. | Property | Description | Type | | --- | --- | --- | @@ -132,6 +140,8 @@ Form.useForm() creates a Form instance, which is used to manage all data states. | resetFields | Reset form prompt state | `() => void` | | submit | method to submit a form for validation | `Promise` | +`Form.useWatch()`, this method will watch specified inputs and return their values. It is useful to render input value and for determining what to render by condition. + ## Theming ### CSS Variables diff --git a/src/packages/form/doc.md b/src/packages/form/doc.md index 2b176efff3..d9619d0048 100644 --- a/src/packages/form/doc.md +++ b/src/packages/form/doc.md @@ -58,6 +58,14 @@ import { Form } from '@nutui/nutui-react' ::: +### useWatch + +:::demo + + + +::: + ### 表单类型 :::demo @@ -120,7 +128,7 @@ import { Form } from '@nutui/nutui-react' ### FormInstance -Form.useForm()创建 Form 实例,用于管理所有数据状态。 +`Form.useForm()`创建 Form 实例,用于管理所有数据状态。 | 属性 | 说明 | 类型 | | --- | --- | --- | @@ -131,6 +139,8 @@ Form.useForm()创建 Form 实例,用于管理所有数据状态。 | resetFields | 重置表单提示状态 | `() => void` | | submit | 提交表单进行校验的方法 | `Promise` | +`Form.useWatch()`此方法将监视指定的输入并返回其值。它对于呈现输入值和确定根据条件呈现的内容很有用。 + ## 主题定制 ### 样式变量 diff --git a/src/packages/form/doc.taro.md b/src/packages/form/doc.taro.md index a6b01d1b5b..748db03665 100644 --- a/src/packages/form/doc.taro.md +++ b/src/packages/form/doc.taro.md @@ -58,6 +58,14 @@ import { Form } from '@nutui/nutui-react-taro' ::: +### useWatch + +:::demo + + + +::: + ### 表单类型 :::demo @@ -120,7 +128,7 @@ import { Form } from '@nutui/nutui-react-taro' ### FormInstance -Form.useForm()创建 Form 实例,用于管理所有数据状态。 +`Form.useForm()`创建 Form 实例,用于管理所有数据状态。 | 属性 | 说明 | 类型 | | --- | --- | --- | @@ -131,6 +139,8 @@ Form.useForm()创建 Form 实例,用于管理所有数据状态。 | resetFields | 重置表单提示状态 | `() => void` | | submit | 提交表单进行校验的方法 | `Promise` | +`Form.useWatch()`此方法将监视指定的输入并返回其值。它对于呈现输入值和确定根据条件呈现的内容很有用。 + ## 主题定制 ### 样式变量 diff --git a/src/packages/form/doc.zh-TW.md b/src/packages/form/doc.zh-TW.md index 8abf1361c3..8725a0a372 100644 --- a/src/packages/form/doc.zh-TW.md +++ b/src/packages/form/doc.zh-TW.md @@ -58,6 +58,14 @@ import { Form } from '@nutui/nutui-react' ::: +### useWatch + +:::demo + + + +::: + ### 表單類型 :::demo @@ -120,7 +128,7 @@ import { Form } from '@nutui/nutui-react' ### FormInstance -Form.useForm()創建 Form 實例,用於管理所有數據狀態。 +`Form.useForm()`創建 Form 實例,用於管理所有數據狀態。 | 屬性 | 說明 | 類型 | | --- | --- | --- | @@ -131,6 +139,8 @@ Form.useForm()創建 Form 實例,用於管理所有數據狀態。 | resetFields | 重置錶單提示狀態 | `() => void` | | submit | 提交錶單進行校驗的方法 | `Promise` | +`Form.useWatch()`此方法將監視指定的輸入並傳回其值。它對於呈現輸入值和確定根據條件呈現的內容很有用。 + ## 主題定制 ### 樣式變量 diff --git a/src/packages/form/index.taro.ts b/src/packages/form/index.taro.ts index 093d5218c8..fdfefdae35 100644 --- a/src/packages/form/index.taro.ts +++ b/src/packages/form/index.taro.ts @@ -2,7 +2,7 @@ import React from 'react' import { Form, FormProps } from './form.taro' import { FormItem } from '../formitem/formitem.taro' import { FormInstance } from './types' -import { useForm } from '@/packages/form/useform.taro' +import { useForm, useWatch } from '@/packages/form/useform.taro' export type { FormItemRuleWithoutValidator, @@ -17,11 +17,13 @@ type CompoundedComponent = React.ForwardRefExoticComponent< > & { Item: typeof FormItem useForm: typeof useForm + useWatch: typeof useWatch } const InnerForm = Form as CompoundedComponent InnerForm.Item = FormItem InnerForm.useForm = useForm +InnerForm.useWatch = useWatch export default InnerForm diff --git a/src/packages/form/index.ts b/src/packages/form/index.ts index 6563f8a986..748c374c25 100644 --- a/src/packages/form/index.ts +++ b/src/packages/form/index.ts @@ -2,7 +2,7 @@ import React from 'react' import { Form, FormProps } from './form' import { FormItem } from '../formitem/formitem' import { FormInstance } from './types' -import { useForm } from '@/packages/form/useform' +import { useForm, useWatch } from '@/packages/form/useform' export type { FormItemRuleWithoutValidator, @@ -17,11 +17,13 @@ type CompoundedComponent = React.ForwardRefExoticComponent< > & { Item: typeof FormItem useForm: typeof useForm + useWatch: typeof useWatch } const InnerForm = Form as CompoundedComponent InnerForm.Item = FormItem InnerForm.useForm = useForm +InnerForm.useWatch = useWatch export default InnerForm diff --git a/src/packages/form/useform.taro.ts b/src/packages/form/useform.taro.ts index 8559e5c5d7..cd84b2a983 100644 --- a/src/packages/form/useform.taro.ts +++ b/src/packages/form/useform.taro.ts @@ -1,4 +1,4 @@ -import { useRef } from 'react' +import { useEffect, useRef, useState } from 'react' import Schema from 'async-validator' import { merge } from '@/utils/merge' import { @@ -11,6 +11,7 @@ import { export const SECRET = 'NUT_FORM_INTERNAL' type UpdateItem = { entity: FormFieldEntity; condition: any } +type WatchCallback = (value: Store, namePath: NamePath[]) => void /** * 用于存储表单的数据 @@ -45,11 +46,10 @@ class FormStore { */ registerField = (field: any) => { this.fieldEntities.push(field) + const namePath = field.props.name + return () => { this.fieldEntities = this.fieldEntities.filter((item) => item !== field) - if (this.store) { - delete this.store[field.props.name] - } } } @@ -90,6 +90,7 @@ class FormStore { if (init) { const nextStore = merge(initialValues, this.store) this.updateStore(nextStore) + this.notifyWatch() } } @@ -117,6 +118,7 @@ class FormStore { item.entity.onStoreChange('update') } }) + this.notifyWatch() } setFieldValue = (name: NamePath, value: T) => { @@ -124,6 +126,7 @@ class FormStore { [name]: value, } this.setFieldsValue(store) + this.notifyWatch([name]) } setCallback = (callback: Callbacks) => { @@ -234,6 +237,7 @@ class FormStore { store: this.store, fieldEntities: this.fieldEntities, registerUpdate: this.registerUpdate, + registerWatch: this.registerWatch, } } } @@ -251,6 +255,30 @@ class FormStore { getInternal: this.getInternal, } } + + private watchList: WatchCallback[] = [] + + private registerWatch = (callback: WatchCallback) => { + this.watchList.push(callback) + + return () => { + this.watchList = this.watchList.filter((fn) => fn !== callback) + } + } + + private notifyWatch = (namePath: NamePath[] = []) => { + if (this.watchList.length) { + let allValues + if (!namePath || namePath.length === 0) { + allValues = this.getFieldsValue(true) + } else { + allValues = this.getFieldsValue(namePath) + } + this.watchList.forEach((callback) => { + callback(allValues, namePath) + }) + } + } } export const useForm = (form?: FormInstance): [FormInstance] => { @@ -265,3 +293,22 @@ export const useForm = (form?: FormInstance): [FormInstance] => { } return [formRef.current as FormInstance] } + +export const useWatch = (path: NamePath, form: FormInstance) => { + const formInstance = form.getInternal(SECRET) + const [value, setValue] = useState() + useEffect(() => { + const unsubscribe = formInstance.registerWatch( + (data: any, namePath: NamePath) => { + const value = data[path] + setValue(value) + } + ) + const initialValue = form.getFieldsValue(true) + if (value !== initialValue[path]) { + setValue(initialValue[path]) + } + return () => unsubscribe() + }, [form]) + return value +} diff --git a/src/packages/form/useform.ts b/src/packages/form/useform.ts index 8559e5c5d7..cd84b2a983 100644 --- a/src/packages/form/useform.ts +++ b/src/packages/form/useform.ts @@ -1,4 +1,4 @@ -import { useRef } from 'react' +import { useEffect, useRef, useState } from 'react' import Schema from 'async-validator' import { merge } from '@/utils/merge' import { @@ -11,6 +11,7 @@ import { export const SECRET = 'NUT_FORM_INTERNAL' type UpdateItem = { entity: FormFieldEntity; condition: any } +type WatchCallback = (value: Store, namePath: NamePath[]) => void /** * 用于存储表单的数据 @@ -45,11 +46,10 @@ class FormStore { */ registerField = (field: any) => { this.fieldEntities.push(field) + const namePath = field.props.name + return () => { this.fieldEntities = this.fieldEntities.filter((item) => item !== field) - if (this.store) { - delete this.store[field.props.name] - } } } @@ -90,6 +90,7 @@ class FormStore { if (init) { const nextStore = merge(initialValues, this.store) this.updateStore(nextStore) + this.notifyWatch() } } @@ -117,6 +118,7 @@ class FormStore { item.entity.onStoreChange('update') } }) + this.notifyWatch() } setFieldValue = (name: NamePath, value: T) => { @@ -124,6 +126,7 @@ class FormStore { [name]: value, } this.setFieldsValue(store) + this.notifyWatch([name]) } setCallback = (callback: Callbacks) => { @@ -234,6 +237,7 @@ class FormStore { store: this.store, fieldEntities: this.fieldEntities, registerUpdate: this.registerUpdate, + registerWatch: this.registerWatch, } } } @@ -251,6 +255,30 @@ class FormStore { getInternal: this.getInternal, } } + + private watchList: WatchCallback[] = [] + + private registerWatch = (callback: WatchCallback) => { + this.watchList.push(callback) + + return () => { + this.watchList = this.watchList.filter((fn) => fn !== callback) + } + } + + private notifyWatch = (namePath: NamePath[] = []) => { + if (this.watchList.length) { + let allValues + if (!namePath || namePath.length === 0) { + allValues = this.getFieldsValue(true) + } else { + allValues = this.getFieldsValue(namePath) + } + this.watchList.forEach((callback) => { + callback(allValues, namePath) + }) + } + } } export const useForm = (form?: FormInstance): [FormInstance] => { @@ -265,3 +293,22 @@ export const useForm = (form?: FormInstance): [FormInstance] => { } return [formRef.current as FormInstance] } + +export const useWatch = (path: NamePath, form: FormInstance) => { + const formInstance = form.getInternal(SECRET) + const [value, setValue] = useState() + useEffect(() => { + const unsubscribe = formInstance.registerWatch( + (data: any, namePath: NamePath) => { + const value = data[path] + setValue(value) + } + ) + const initialValue = form.getFieldsValue(true) + if (value !== initialValue[path]) { + setValue(initialValue[path]) + } + return () => unsubscribe() + }, [form]) + return value +}