在使用React+ant design进行开发时通常使用Form组件,但是很多时候我们某一个字段是二维数组。例如这样:
export const searchOptionContext = atom({
key: "article-list-option",
default: {
/** 发布人 管理员或者用户*/
auth: undefined,
/** 设置正序还是倒序*/
sort: ["create_time", "desc"],//这里
/** 时间线,查询某某之后create_time的文章*/
deadline: undefined,
/** 根据ID进行查询*/
article_id: undefined,
/** 发布者ID*/
author_id: undefined,
},
});
但是表单每个item只对应了一个字段,怎么对多维数组中的每个元素进行设置呢?在仔细阅读文档后发现antd提供了一个list子组件来遍历多维数组。
在开发中只需要采取map对多维数组进行遍历即可:
通过索引值进行条件渲染,或者定义一个数组使用map的index参数进行渲染,不在需要条件判断。使用field中提供的key也可以,也是索引值。
<Form.List name="sort">
{fields =>
fields.map((field, index) => (
<Form.Item {...field} label={index == 0 ? "排序条件" : "规则"}>
<Select value={option.sort[index]} style={{ width: "120px" }}>
{index == 0 ? (
<>
<Option value="create_time">发布时间</Option>
<Option value="update_time">更新时间</Option>
<Option value="view_count">阅读数</Option>
</>
) : (
<>
<Option value="desc">降序</Option>
<Option value="asc">升序</Option>
</>
)}
</Select>
</Form.Item>
))
}
</Form.List>