antd form.setFieldsValue问题总结

antd form.setFieldsValue问题总结

1.嵌套组件form实例如何传递

想要使用form.setFieldsValue就需要实例出form对象,但是如果是如下的嵌套组件结构该怎么传递呢,antd官方给我们提供了方法

ts 复制代码
const [form] = Form.useForm()
html 复制代码
...
<Form layout="vertical" form={form}>
    <Card title="经营目标" extra={<Button type="primary">保存</Button>}>
        <Tabs
        animated={{ inkBar: true, tabPane: true }}
        onChange={onChange}
        items={items}
        tabBarGutter={8.13}
        />
    </Card>
</Form>
...

子组件则只需要使用官方提供的Form.useFormInstance()即可获得上下文中的form

ts 复制代码
...
  // 获取当前上下文正在使用的 Form 实例
  const form = Form.useFormInstance();
...
  // 改变对应input的值 
  const profit = () => {
    // setFieldsValue({name:"value"})
    form.setFieldsValue({
      SCProfitMargin: '11111', // 对应第一个SCProfitMargin input
      VCProfitMargin: '22222',  // 对应第二个VCProfitMargin input
      SCendProfitMargin: "3333333",
      VCendProfitMargin: "444444"
    })
  }
...

2.form.setFieldsValue不生效可能是这个原因

当你使用form.setFieldsValue重新设置input的值的时候,他也许不会生效,看看你的html结构是否是这样的

这样的结构Form.Item不会关联到指定input,所以官方又提供了一个新的方案

html 复制代码
    <Form.Item
        name="target"
        label='Amazon'
        rules={[{ required: true }]}
    >
        <Input.Group compact>
            <Input
            onBlur={lowPriceOnblur}
            style={{ width: '185px', height: '32px' }}
            defaultValue="默认值"
            />
            <Button type="primary">打开</Button>
        </Input.Group>
    </Form.Item>

更改后

noStyle是为了让内层Form.Item失去样式不造成冲突

html 复制代码
    <Form.Item
        label='Amazon'
    >
        <Input.Group compact>
            <Form.Item name="target" noStyle rules={[{ required: true }]} >
                <Input
                onBlur={lowPriceOnblur}
                style={{ width: '185px', height: '32px' }}
                defaultValue="默认值"
                />
            </Form.Item>
            <Button type="primary">打开</Button>
        </Input.Group>
    </Form.Item>

2.more...

相关推荐
淼淼爱喝水6 分钟前
基于DOM型XSS漏洞与利用实验教程
前端·xss·dom·dvwa
Aotman_37 分钟前
Element UI 表格搜索高亮
前端·javascript·vue.js·ui·elementui
yqcoder1 小时前
[特殊字符] Vue 3 中 Keep-Alive 对生命周期的影响:深度解析
前端·javascript·vue.js
jiayong231 小时前
第 33 课:任务看板视图(按状态分列)与本地持久化
开发语言·前端·javascript·学习
GISer_Jing2 小时前
Dify可视化编排:技术架构与实战指南
前端·人工智能·ai编程
宇宙realman_9992 小时前
DSP28335-FlashAPI使用
linux·前端·python
踩着两条虫2 小时前
VTJ 平台六大设计模式落地实战指南
开发语言·前端·人工智能·低代码·设计模式·重构·架构
Yeats_Liao2 小时前
后台 Sidebar 伸缩交互(PC + 移动端)实现
前端·javascript·css·html5
MXN_小南学前端2 小时前
computed 计算属性详解:触发时机、实战场景、Vue2 与 Vue3 对比
前端·javascript·vue.js
isNotNullX2 小时前
数据大屏怎么做?数据大屏有哪四个核心环节
开发语言·前端·javascript