ant中select回显value问题及解决
作者:lyce_liu
在React项目中使用Ant Design的Select组件时,如果设置了自定义的`fieldNames`属性,选中项的label会显示,但回填到选择框时显示的是value值,解决方法是使用`optionLabelProp`属性指定回填到选择框的Option属性为自定义的label字段
问题描述
react项目中使用ant的select选择器遇到的问题,选中某一项后,想要的效果是显示选中项的label,但回填到选择框却为为value值。

原因分析
因为使用了fieldNames属性自定义节点 label、value、options 字段{ label: “dictLabel”, value: “dictValue” }。
<Select
showSearch
allowClear
fieldNames={{ label: "dictLabel", value: "dictValue" }}
options={selectOptions}
filterOption={(input, option) =>
(option?.dictLabel ?? '').toLowerCase().includes(input.toLowerCase())
}
notFoundContent="暂无数据"
/>`
解决方案
使用 optionLabelProp 属性指定回填到选择框的 Option 属性,默认是children,
需要optionLabelProp 设置为自定义的label字段即可,即在select中添加属性optionLabelProp ="dictLabel"
fieldNames={{ label: "dictLabel", value: "dictValue" }}
optionLabelProp="dictLabel" //optionLabelProp等于自定义label
官方文档:4x.ant.design定制回填内容
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
