Author: jwensh
Date: 2021.08.27
文章目录
React 项目实践中 antd table 中 select 的设值更新问题
问题
问题 1. 默认值问题(没有显示placeholer)
描述:
正常情况下,表格一列下不同行,可能有不同值,这些值设值到 select 希望展示不同的样式; 如空值(0;’’),应该显示
placeholder
<Select
showSearch
suffixIcon={<SearchOutlined />}
style={{ width: 150 }}
placeholder="请选择设置项"
>
...
</Select>
- 上面的写法会显示
placeholder
内容,但是没有进行设值操作
// react + typescript
render : (text: React.ReactNode, record: TaskListType) => (
<Select
showSearch
value={text as string}
suffixIcon={<SearchOutlined />}
style={{ width: 150 }}
placeholder="请选择设置项"
>
...
</Select>
)
- 上面
text
是 antd table column 传过来的值,且值是空值 - 结果:还是不能展示
placeholder
- 这里直接说结论吧,不吃丸子了
select 的 value、defaultValue、key
- defaultValue 和 value 区别 ?
- defautValue 指定默认值,也就是我们页面加载时,通过 dataSource 设置进来的数据;
- value 指定当前选中值,通过下拉列表 option 选中后的值;
问题:
使用defaultValue会有一个问题,对页面进行数据处理后数据没有及时更新,需要用value
解决此问题
解决:空值展示 placeholder
,需要设置为 undefined
// react + typescript
render : (text: React.ReactNode, record: TaskListType) => (
<Select
showSearch
value={record.setting === '' ? undefined : record.setting}
suffixIcon={<SearchOutlined />}
style={{ width: 150 }}
placeholder="请选择设置项"
>
...
</Select>
)
- 官网看到:
export type SelectValue = RawValue | RawValue[] | LabeledValue | LabeledValue[] | undefined;
- 也实验过
null
ts eslint 直接提示不行,所以,想要了解其深度原理,可看源码
问题2. 更新一行数据后,select 的 selectValue 状态没有变化
更新 select 的值有两个渠道
- 1.通过下拉框选择 option
- 2.其他事件更新了当前行数据(如: setting=‘user’ => setting=’’)
第二个方案应该是我们经常用的,如下写法是不生效的
render : (text: React.ReactNode, record: TaskListType) => (
<Select
showSearch
value={record.setting === '' ? undefined : record.setting}
suffixIcon={<SearchOutlined />}
style={{ width: 150 }}
placeholder="请选择设置项"
>
...
</Select>
)
// 更新操作是 Hooks 函数直接 setTaskList([...dataSource])
不管使用 value
还是 defaultValue
都不生效;
解决:为 select 添加一个 key
的 props
实现非受控组件(用defaultValue),两个办法
- 第一个服务端没有返回数据的时候,不 render Select,render 一个占位的 placeholder;
- 给 Select 加一个 key,值为 defaultValue;
render : (text: React.ReactNode, record: TaskListType) => (
<Select
showSearch
value={record.setting === '' ? undefined : record.setting}
key={record.setting}
suffixIcon={<SearchOutlined />}
style={{ width: 150 }}
placeholder="请选择设置项"
>
...
</Select>
)
问题3. antd table 局部一行数据更新
// 某一行数据更新调用的方法
const handleSave = (row: TaskListType) => {
// 从新将数据 copy 一波
const newData = [...dataSource];
// 找到操作更新的数据在源数据中的下标
const index = newData.findIndex(item => row.key === item.key);
// 找到对应更新的数据
const item = newData[index];
// 将新数据中的数据进行更新
newData.splice(index, 1, {
...item,
...row,
});
// useState 更新即可
setTaskList(newData);
};