React Native ModalDropdown选中后低索引选项消失问题求助
解决react-native-modal-dropdown选中选项后低索引选项消失的问题
这个问题是react-native-modal-dropdown的默认行为导致的——组件默认会将选中的选项从下拉列表的原位置移除(keepSelectedInList属性默认值为false),同时如果未明确同步选中状态,可能引发列表显示异常。
解决方案
添加两个关键配置即可修复:
keepSelectedInList={true}:强制保留选中选项在下拉列表的原位置,不会被移除- 绑定
selectedIndex:让组件的选中状态与你的外部状态同步,避免内部状态混乱
修改后的代码示例
import React, { useState } from 'react'; import ModalDropdown from 'react-native-modal-dropdown'; const RankingPage = () => { const [selectedIndex, setSelectedIndex] = useState(-1); // -1表示未选中任何选项 const options = ['option1', 'option2', 'option3']; const handleQuestChange = (index) => { setSelectedIndex(index); }; return ( <ModalDropdown options={options} defaultValue="Select an option ▼" onSelect={(index) => handleQuestChange(index)} selectedIndex={selectedIndex} keepSelectedInList={true} // 核心配置:保留选中项在列表中 /> ); };
补充说明
如果需要保留selectedOption状态而非selectedIndex,可以通过选项索引映射实现同步:
import React, { useState } from 'react'; import ModalDropdown from 'react-native-modal-dropdown'; const RankingPage = () => { const [selectedOption, setSelectedOption] = useState(null); const options = ['option1', 'option2', 'option3']; const handleQuestChange = (index) => { setSelectedOption(options[index]); }; return ( <ModalDropdown options={options} defaultValue="Select an option ▼" onSelect={(index) => handleQuestChange(index)} selectedIndex={selectedOption ? options.indexOf(selectedOption) : -1} keepSelectedInList={true} /> ); };
另外,建议检查并升级react-native-modal-dropdown到最新版本,避免旧版本的潜在bug。
内容的提问来源于stack exchange,提问作者Camille
相关产品推荐
相关产品推荐

