【问题标题】:Ant Design Table component with editable rows and controlled inputs具有可编辑行和受控输入的 Ant Design Table 组件
【发布时间】:2021-03-02 01:46:08
【问题描述】:
我正在尝试使用 Ant Design 制作一个带有受控输入的表格组件。
我从 Antd doc:Table with editable rows 开始,然后 1) 将代码模块化 2) 使用 Hooks 和 3) 删除了 Antd Forms 的使用。
我有 4 个组件
在表格组件内部,我有 3 个状态:
- editing ==> 当编辑设置为 TRUE 时,该行可编辑并接受用户输入
- currentRowValues ==> currentRowValues 将保存可编辑行的当前用户输入
- rowList ==> 按下保存后,currentRowValues 将填充 rowList
但是当我按下给定行的编辑图标时:
- InputNumber 将丢失当前值,并且不会根据用户输入而改变
- DatePicker 将保存该值,但不会根据用户输入进行更新
我想让 InputNumber 和 DatePicker 在行处于编辑状态时保持初始值,反映用户输入并在用户点击保存时更新行列表。
我已经多次调整代码但无法使其工作
这里是CodeSandbox
【问题讨论】:
标签:
reactjs
react-hooks
antd
react-state
controlled-component
【解决方案1】:
为满足指定要求,需对代码稍作改动
- 点击编辑按钮时,需要将当前行的值复制到currentRowValues中
const editRow = (rowKey) => {
setEditingKey(rowKey);
setCurrentRowValues({ ...rowList.find((row) => row.key === rowKey) });
};
- 要更改数据,您不仅需要传递值,还需要传递参数的名称
const handleInputChange = (value, dataIndex) => {
setCurrentRowValues((old) => ({ ...old, [dataIndex]: value }));
};
- 您需要更改传递给 InputNode 组件的参数
<InputNode
style={{ margin: 0 }}
inputType={inputType}
value={currentRowValues[dataIndex]}
handleInputChange={(value) => {
handleInputChange(value, dataIndex);
}}
/>
4)为了正确存储日期,需要在 DatePicker 组件中将它们转换为字符串
<AntDatePicker
picker="month"
size="small"
allowClear="true"
placeholder={placeholder}
format="YYYY-MM"
value={value}
onChange={(e) => handleInputChange(e.format("MMM YYYY"))
{...restProps}
/>
这是一个老问题,但我希望这对那些将来会面临类似问题的人有所帮助
链接到codesandbox