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

相关推荐
前端 贾公子2 小时前
pnpm 的 resolution-mode 配置 ( pnpm 的版本解析)
前端
伍哥的传说3 小时前
React 自定义Hook——页面或元素滚动到底部监听 Hook
前端·react.js·前端框架
麦兜*4 小时前
Spring Boot 集成Reactive Web 性能优化全栈技术方案,包含底层原理、压测方法论、参数调优
java·前端·spring boot·spring·spring cloud·性能优化·maven
知了一笑5 小时前
独立开发第二周:构建、执行、规划
java·前端·后端
UI前端开发工作室5 小时前
数字孪生技术为UI前端提供新视角:产品性能的实时模拟与预测
大数据·前端
Sapphire~5 小时前
重学前端004 --- html 表单
前端·html
TE-茶叶蛋6 小时前
Flutter、Vue 3 和 React 在 UI 布局比较
vue.js·flutter·react.js
遇到困难睡大觉哈哈6 小时前
CSS中的Element语法
前端·css
Real_man6 小时前
新物种与新法则:AI重塑开发与产品未来
前端·后端·面试
小彭努力中6 小时前
147.在 Vue3 中使用 OpenLayers 地图上 ECharts 模拟飞机循环飞行
前端·javascript·vue.js·ecmascript·echarts