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...

相关推荐
We་ct13 小时前
LeetCode 77. 组合:DFS回溯+剪枝,高效求解组合问题
开发语言·前端·算法·leetcode·typescript·深度优先·剪枝
KerwinChou_CN13 小时前
什么是流式输出,后端怎么生成,前端怎么渲染
前端
爱上妖精的尾巴13 小时前
8-20 WPS JS宏 正则表达式-懒惰匹配
服务器·前端·javascript
网络点点滴13 小时前
组件通信props方式
前端·javascript·vue.js
二十雨辰14 小时前
[小结]-线上Bug监控
前端·bug
前端技术14 小时前
【鸿蒙实战】从零打造智能物联网家居控制系统:HarmonyOS Next分布式能力的完美诠释
java·前端·人工智能·分布式·物联网·前端框架·harmonyos
CHU72903514 小时前
指尖践行环保——旧衣服回收小程序前端功能玩法详解
前端·小程序
LawrenceLan14 小时前
38.Flutter 零基础入门(三十八):网络请求实战 http、dio —— 获取列表与刷新 UI
开发语言·前端·flutter·dart
csdn_aspnet14 小时前
Asp.Net Core 10.0 中的 Blazor 增强功能
前端·后端·asp.net·blazor·.net10
SuperEugene14 小时前
Excel 上传解析 + 导出实战:Vue+xlsx 避坑指南|Vue生态精选
前端·javascript·vue.js·excel·xlsx·vxetable