本篇文章主要是关于如何采用Form useWatch Hooks实现表单实时预览效果
一、应用场景
使用的场景主要来源于工作或者我们具体的项目需求,比如当需要边填写表单并实现边预览可以采用Form useWatch Hooks
的方式。
二、useWatch
4.20.0 新增,用于直接获取 form 中字段对应的值。通过该 Hooks 可以与诸如 useSWR 进行联动从而降低维护成本
import React from 'react';
import { Form, Input, InputNumber, Typography } from 'antd';
const Demo = () => {
const [form] = Form.useForm<{ name: string; age: number }>();
const nameValue = Form.useWatch('name', form);
return (
<>
<Form form={form} layout="vertical" autoComplete="off">
<Form.Item name="name" label="Name (Watch to trigger rerender)">
<Input />
</Form.Item>
<Form.Item name="age" label="Age (Not Watch)">
<InputNumber />
</Form.Item>
</Form>
<Typography>
<pre>Name Value: {nameValue}</pre>
</Typography>
</>
);
};
export default Demo;
三、关键代码
const [form] = Form.useForm<{ name: string; age: number }>();
// 获取表单name字段的是实时值,从而进行渲染展示。
const nameValue = Form.useWatch('name', form);