Leanote's Blog
I love Leanote!
Toggle navigation
Leanote's Blog
Home
Chrome
Git
Linux
Windows
Others
工具大全
VsCode
Expo
Html
JavaScript
Npm
Node
Mock
React-Native
React
TypeScript
小程序
插件
正则
Dva
Ant-Design-React
Umi
Vue
Vux
Ant-Design-Vue
Http
Java
flutter
开发小工具
About Me
Archives
Tags
Form控制Table的值
2025-11-10 02:47:00
0
0
0
admin
## 1. 使用 `Form.List` 动态控制 `Table` 数据 (最推荐的方式,尤其是编辑型表格) 思路 - 用 `Form.List` 来存储一组列表数据(比如表格的每一行); - 每一行的数据作为一个对象; - `Table` 的数据源(dataSource)直接绑定到 `form.getFieldValue('listName')`; - 每列通过 `Form.Item` 渲染可编辑单元格。 ### 示例 ```tsx import React from 'react'; import { Form, Input, InputNumber, Button, Table } from 'antd'; const EditableTable = () => { const [form] = Form.useForm(); return ( <Form form={form} initialValues={{ users: [{ name: '张三', age: 18 }] }}> <Form.List name="users"> {(fields, { add, remove }) => { const columns = [ { title: '姓名', dataIndex: 'name', render: (_, __, index) => ( <Form.Item name={[index, 'name']} style={{ marginBottom: 0 }}> <Input /> </Form.Item> ), }, { title: '年龄', dataIndex: 'age', render: (_, __, index) => ( <Form.Item name={[index, 'age']} style={{ marginBottom: 0 }}> <InputNumber /> </Form.Item> ), }, { title: '操作', render: (_, __, index) => ( <Button onClick={() => remove(index)}>删除</Button> ), }, ]; return ( <> <Table pagination={false} columns={columns} dataSource={fields} rowKey="key" /> <Button onClick={() => add()}>新增</Button> </> ); }} </Form.List> <Button onClick={() => console.log(form.getFieldsValue())} type="primary" > 提交 </Button> </Form> ); }; ``` ### 2. 使用 `shouldUpdate` + `getFieldValue` ```tsx const columns = [ { title: '姓名', dataIndex: 'name', render: (_, __, index) => ( <Form.Item name={['users', index, 'name']} style={{ marginBottom: 0 }} rules={[{ required: true, message: '请输入姓名' }]} > <Input /> </Form.Item> ), }, { title: '启用', dataIndex: 'active', render: (_, __, index) => ( <Form.Item name={['users', index, 'active']} valuePropName="checked" style={{ marginBottom: 0 }} > <Switch /> </Form.Item> ), }, ] <Form.Item shouldUpdate> {({ getFieldValue }) => ( <Table columns={columns} dataSource={getFieldValue('user') || []} /> )} </Form.Item> ``` ### 3. 使用 `valuePropName="dataSource"` ```tsx const columns = [ { title: '姓名', dataIndex: 'name', render: (_, __, index) => ( <Form.Item name={['users', index, 'name']} style={{ marginBottom: 0 }} rules={[{ required: true, message: '请输入姓名' }]} > <Input /> </Form.Item> ), }, { title: '启用', dataIndex: 'active', render: (text, __, index) => ( <Form.Item name={['users', index, 'active']} valuePropName="checked" style={{ marginBottom: 0 }} initialValue={text} // 初始值, 仅第一次显示 > <Switch /> </Form.Item> ), }, ] <Form.Item valuePropName="dataSource" name="user"> <Table columns={columns} /> </Form.Item> ```
Pre:
自定义表格组件单元格触发接口失败时恢复数据
Next:
Docker Desktop stopped
0
likes
1
Weibo
Wechat
Tencent Weibo
QQ Zone
RenRen
Submit
Sign in
to leave a comment.
No Leanote account?
Sign up now.
0
comments
More...
Table of content
No Leanote account? Sign up now.