使用antd中的select下拉框,遇到個小問題,後臺管理系統中,使用下拉框,一般不會是簡單的就直接使用select中的value值,而是會使用id或者value中文對應的keyword,並且這個在option中的value值也是可能重複的
1.效果圖
2.select相關代碼
- 我這裏用的是react
let list = [
{
title: '普通會員',
id: 1
},{
title: '測試專用人員',
id: 2
}, {
title: '測試專用人員',
id: 3
}
];
let currentEditOption: {
roleId: '',
title: '',
};
<Select
value={currentEditOption.title}
style={{width: '70%'}}
suffixIcon={<Icon type="caret-down"/>}
>
{
list.map((item:any) =>
<Option key={item.id} value={item.title}>{item.title}</Option>
)
}
</Select>
- 下拉框事件
handleSelect = (value:any, option: any) => {
console.log(value)
/* option返回的是option對應的整個對象 */
console.log(option)
};
- 此時,並沒有出現問題,但是,一旦list中有兩項的title字段是以一樣的,瀏覽器就報警告
Warning: Encountered two children with the same key, `.$測試專用人員`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.
- 按照我的理解,select下拉框應該是去檢測key值而不檢測value值的,但是,我設置key值後,還是會檢測value值
- 當然,你這裏可以去掉value值的設置,它也能實現下拉選擇後,onchang能獲取到對應的數據,但我想實現的是,當select中有選中值的時候,option選項中對應的值應該是選中狀態的
- 然後,我就嘗試了多次,還設置過optionLabelProp這個屬性,沒有用,開始的時候,我也設置過labelInValue,不過,我傳入value值不是對象,導致我開始嘗試的時候放棄了labelInValue屬性的設置,後面又重新嘗試,發現OK了,並且,這個時候,必須同時設置option中的value和key屬性值
<Select
labelInValue
value={{key: currentItem.roleId, label:currentItem.title}}
style={{width: '70%'}}
onChange={handleSelect}
suffixIcon={<Icon type="caret-down" />}
getPopupContainer={(triggerNode: any) => triggerNode.parentNode}
>
{
list.map((item:any) =>
<Option key={item.id} value={item.id}>{item.title}</Option>
)
}
</Select>
- 下拉框的選擇事件
/* 定義下拉框選擇 */
handleSelect = (value:any, option: any) => {
/* 此時value值是一個對象 */
console.log(value)
/* option返回的是option對應的整個對象 */
console.log(option)
};
3.option組件出現位置偏移
- 在彈窗組件中使用select時,當點擊Select組件出現下拉選項後滾動原始頁面,出現下拉選項和Select框分離現象
- 這個時候就可以用官方提供的方式來防止位置偏移
- 在select中直接加入這個方法getPopupContainer={triggerNode => triggerNode.parentNode}
4.在vue中使用element-ui時,也出現過這種value值是對象的情況
- vue項目中使用element-ui下拉框選項值爲對象時報錯
- 在這篇文章裏我記錄了vue 的情況